[英]Using scipy to integrate a function?
我正在嘗試使用SciPy集成此功能:
y(x)=(e ^ -ax)* cos(x)在0和4pi之間。
這是我到目前為止的代碼:
from numpy import *
from scipy.integrate import simps
a = 0
x = linspace(0 , 4*pi, 100)
y = (e^-(a*x))*cos(x)
integral_value = simps(y,x)
print integral_value
但是,它似乎不起作用。 任何幫助,將不勝感激,謝謝!
好吧,如果您運行該程序,則會得到以下錯誤:
TypeError:輸入類型不支持ufunc'bitwise_xor',並且根據強制轉換規則“ safe”,不能將輸入安全地強制轉換為任何受支持的類型
因此,您知道問題出在函數中的^
(按位異或)。 在Python中, 使用**
取指數 。
如果有人寫道:
y = (e**-(a*x))*cos(x)
取而代之的是:
>>> print integral_value
-0.000170200006112
完整程序:
from numpy import *
from scipy.integrate import simps
a = 0
x = linspace(0 , 4*pi, 100)
y = (e**-(a*x))*cos(x)
integral_value = simps(y,x)
print integral_value
您還可以通過以下方式顯式使用numpy
函數:
from numpy import *
from scipy.integrate import simps
a = 0
x = linspace(0 , 4*pi, 100)
y = exp(-a*x)*cos(x)
integral_value = simps(y,x)
print integral_value
為了提高精度,可以增加點數(100不是那么多)。
import numpy as np
import math
from scipy.integrate import simps
a = 0
x = np.linspace(0 , 4*math.pi, 100)
#create a vectorized function which can be applied directly to an array
fn = np.vectorize(lambda x: math.exp(-a*x)*math.cos(x))
y = fn(x)
integral_value = simps(y, x)
print integral_value
這確實產生-0.000170200006112
值。 請注意,對於a=0
,積分等於零,因此要獲得“更緊密的”關系,您需要細化網格...
用大錘子開裂螺母...
>>> from sympy import *
>>> var('a x')
(a, x)
>>> y = exp(-a*x)*cos(x)
>>> y.subs(a,0)
cos(x)
發現在給定的時間間隔內積分為0(零)是否會讓我們感到驚訝?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.