天天看點

octave下實作積分/求解微分方程

我電腦是AMD的不是Intel的,是以matlab很多功能用不了(矩陣乘法都用不了),虛拟機也沒工夫折騰,找了octave來替代。

首先安裝 symbolic包(要求已安裝好Python3的SymPy庫)

pkg install -forge symbolic      

使用pkg list可以看到symbolic已經安裝上了

然後導入這個package

pkg load symbolic      

定義一個sym試試

>> sym x
Symbolic pkg v2.7.1: Python communication link active, SymPy v1.1.1.
ans = (sym) x      

定義一個函數

>> function y = f (x)
y = exp(x);
endfunction      

對函數f從負無窮到0做定積分

>> [v, ier, nfun, err] = quad("f",-inf,0)
v =  1.0000
ier = 0
nfun =  135
err =  0.000000000058426      

官方文檔大意:

積分結果傳回給q,如果ier是0表示積分成功,nfun是建立的function evaluations的數量,err是誤差

q = quad (f, a, b)

[q, ier, nfun, err] = quad (…)

a and b are the lower and upper limits of integration. Either or both may be infinite.

The result of the integration is returned in q.

ier contains an integer error code (0 indicates a successful integration).

nfun indicates the number of function evaluations that were made.

err contains an estimate of the error in the solution.

如果是不定積分,和matlab一樣用的是int函數求,就是有點慢,而且輸出的符号有點好笑(?)不過octave安裝很友善可以原諒

>> syms x
>> y = 1/(1+cos(x))^2;
>> int(y)
ans = (sym)

     3/x\      /x\
  tan |-|   tan|-|
      \2/      \2/
  ------- + ------
     6        2

>>      

同樣的,使用int函數也可以求定積分,也是慢一點,quad函數求出來的比較快

使用vpa(s,5)将定積分的結果取為小數點後五位的具體數值

>> s=int(y,1,2)
s = (sym)

                  3           3
    tan(1/2)   tan (1/2)   tan (1)   tan(1)
  - -------- - --------- + ------- + ------
       2           6          6        2

>> vpa(s,5)
ans = (sym) 1.1080
>>      

參考​​這篇文章​​,使用octave還可以matlab相容地求解微分方程

pkg load symbolic;
a=1;b=0.1;
syms k(t);
syms v(t);

F1 = (diff(k,t) + b*k == 0);
cond1 = k(0) == 2;
r1=dsolve(F1,cond1)      
warning: passing floating-point values to sym is dangerous, see "help sym"
warning: called from
    double_to_sym_heuristic at line 50 column 7
    sym at line 379 column 13
    mtimes at line 65 column 5
    mtimes at line 61 column 5
    my_week14 at line 9 column 4
r1 = (sym)

            -t
            ---
             10
  k(t) = 2*e