numpy 如何将两个函数f(x,n)和f(x,m)相加并对这两个函数的乘积求积分?

oug3syen  于 2023-03-30  发布在  其他
关注(0)|答案(3)|浏览(71)

我想集成两个函数的乘积,但似乎我一直得到一个错误
属性错误:“穆尔”对象没有属性“cos”

import numpy as np
import sympy as sp

x = sp.symbols('x')

dp_xi = []
dp_eta = []

        
for n in range (1,5,1):
    for m in range (1,5,1):
        dp_xi.append(np.cos((n-2)*(np.pi/180)*x)*(n-2)*np.pi/180)
        dp_eta.append(np.cos((m-2)*(np.pi/180)*x)*(m-2)*np.pi/180)
                   
        df_xi = sum(dp_xi)
        df_eta = sum(dp_eta)

I = sp.integrate(df_xi*df_eta, (x, 0, 1))

print("I=",I)

有什么想法吗谢谢
我试着用sp代替np但积分不起作用

t9aqgxwy

t9aqgxwy1#

如前所述,如果要使用解析积分,则应仅使用符号。

n = sp.symbols('n')
f = sp.cos((n-2)*(sp.pi/180*x)*(n-2)*sp.pi/180)
sp.integrate(f, (x, 0, 1))
n6lpvg4x

n6lpvg4x2#

完整的错误消息在哪里?
看看我在运行你的代码时得到了什么

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
AttributeError: 'Mul' object has no attribute 'cos'

The above exception was the direct cause of the following exception:

TypeError                                 Traceback (most recent call last)
Cell In[25], line 9
      7 for n in range (1,5,1):
      8     for m in range (1,5,1):
----> 9         dp_xi.append(np.cos((n-2)*(np.pi/180)*x)*(n-2)*np.pi/180)
     10         dp_eta.append(np.cos((m-2)*(np.pi/180)*x)*(m-2)*np.pi/180)
     12         df_xi = sum(dp_xi)

TypeError: loop of ufunc does not support argument 0 of type Mul which has no callable cos method

它指向包含np.cos的行。自己运行该表达式:

In [26]: np.cos((n-2)*(np.pi/180)*x)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
AttributeError: 'Mul' object has no attribute 'cos'

The above exception was the direct cause of the following exception:

TypeError                                 Traceback (most recent call last)
Cell In[26], line 1
----> 1 np.cos((n-2)*(np.pi/180)*x)

TypeError: loop of ufunc does not support argument 0 of type Mul which has no callable cos method

去掉cos,我们看到的参数是:

In [28]: print((n-2)*(np.pi/180)*x)
-0.0174532925199433*x

简短的回答,正如其他人解释的那样,np.cos不能用于sympy.symbol或表达式。
sympy自己的cos运行,但是,由于x仍然是一个符号,它不会尝试返回一个数值:

In [30]: print(sp.cos((n-2)*(np.pi/180)*x))
cos(0.0174532925199433*x)

使用sp代替:

In [33]: print(df_xi)
2*pi*cos(pi*x/90)/45

In [34]: print(df_eta)
2*pi*cos(pi*x/90)/45

和积分:

In [35]: I = sp.integrate(df_xi*df_eta, (x, 0, 1))
In [37]: print(I)
8*pi*(sin(pi/90)*cos(pi/90)/2 + pi/180)/45
gxwragnw

gxwragnw3#

如果你使用sum的代码,你的代码可以很好地使用sp而不是np。(另外,由于每个表达式只依赖于一个循环变量,所以不需要双循环。)

import sympy as sp

x = sp.symbols('x')

a = [sp.cos((n-2)*(sp.pi/180)*x)*(n-2)*sp.pi/180) for n in range(1, 5)]
                   
df_xi = 4*sum(a)
df_eta = df_xi.subs(n, m)

I = sp.integrate(df_xi*df_eta, (x, 0, 1))

print("I=",I)

产出

I= 8*pi*(sin(pi/90)*cos(pi/90)/2 + pi/180)/45

相关问题