sympy AttributeError:'Pow'对象没有属性'sin' [英] sympy AttributeError: 'Pow' object has no attribute 'sin'

查看:253
本文介绍了sympy AttributeError:'Pow'对象没有属性'sin'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读此SO帖子,其中指出名称空间冲突是导致此错误的原因之一.我经常陷入这个错误.因此,我想了解这里到底发生了什么?图书馆的期望是什么?

I have read this SO post which says namespace conflict is one reason for this error. I am falling to this error frequently. So, I'd like to learn what exactly is happening here? What is expected by the library?

fun = lambda x: 4*x*(np.sin(x**2) - 3)*np.cos(x**2)来自一个测试用例,因此实际上我必须将其用作函数"fun".抱歉,该信息丢失.请讨论遵守此约束条件.

fun = lambda x: 4*x*(np.sin(x**2) - 3)*np.cos(x**2) comes from a test case, so practically I am bound to use it as function 'fun'. Sorry for missing that information. Kindly discuss respecting this constraint.

这是一个错误再现代码,而不是完整的脚本. 任务是计算输入函数的微分,该输入函数可以通过使用摄动∆ = 10 -8的前向差分近似来计算numpy数组.

This is an error reproducing code, not the full script. Task is to calculate differentiation of an input function that can evaluate numpy arrays by using a forward difference approximation with a perturbation ∆=10 −8.

代码:

import sympy
import numpy as np 

# TESTING...
x = sympy.Symbol('x')
fun = lambda x:  4*x*(np.sin(x**2) - 3)*np.cos(x**2)  
print fun
h = 10e-8  #perturbation
print fun(x)
print fun(x+h)
df = (fun(x+h) - fun(x)) / h
print "diff is:", df

错误:

<function <lambda> at 0x000000001068E2E8>
Traceback (most recent call last):

  File "<ipython-input-75-0582d8ebb11b>", line 1, in <module>
    runfile('D:/test_hw3.py', wdir='D:')

  File "D:\anaconda\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
    execfile(filename, namespace)

  File "D:\anaconda\lib\site-packages\spyder\utils\site\sitecustomize.py", line 87, in execfile
    exec(compile(scripttext, filename, 'exec'), glob, loc)

  File "D:/test_hw3.py", line 23, in <module>
    print fun(x)

  File "D:/test_hw3.py", line 20, in <lambda>
    fun = lambda x:  4*x*(np.sin(x**2) - 3)*np.cos(x**2)
AttributeError: 'Pow' object has no attribute 'sin'

推荐答案

您应该使用

You are supposed to use sympy.sin/cos instead of np.sin/cos. Numpy does not know how to work with sympy expressions.

fun = lambda x: 4 * x * (sympy.sin(x**2) - 3) * sumpy.cos(x**2)  

另一方面,如果必须保留np.sin,则应该 not 发送一个sympy变量到fun.相反,df应该本身就是一个函数.

On the other hand, if you must keep np.sin, then you should not send a sympy variable to fun. Instead, df should become a function itself.

fun = lambda x:  4*x*(np.sin(x**2) - 3)*np.cos(x**2)  
h = 1e-8

df = lambda x: (fun(x+h) - fun(x)) / h

# usage:
df( np.array([1.0, 2.0, 3.0, 4.0]) )


顺便说一句,sympy已经有一个 diff 函数来计算导数.


BTW, sympy already has a diff function to compute the derivative.

df = sympy.diff(fun(x), x)

这篇关于sympy AttributeError:'Pow'对象没有属性'sin'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆