python - Python:sympy TypeError:无法将表达式转换为浮点数
问题描述
目前,我正在研究一个计算器,在确定定积分时,它的工作原理类似于“真正的”计算器。
目前我可以让它与诸如
sin(x)
cos(x)
e**x
n*x**x
但是,它不会接受math.sqrt(x)
我的代码中的函数,它只是声明,
File "C:\Users\Nikolai Lund Kühne\.spyder-py3\integration.py", line 6, in <module>
print(series(math.sqrt(x), x, x0=0, n=6))
File "C:\ProgramData\Anaconda3\lib\site-packages\sympy\core\expr.py", line 327, in __float__
raise TypeError("can't convert expression to float")
TypeError: can't convert expression to float
我的代码是:
from sympy.functions import sin,cos
from sympy.abc import x
from sympy import series
from pprint import pprint
# Indsæt her funktionen f(x), variablen x, udviklingspunktet x0 og antal led n
print(series(math.sqrt(x), x, x0=0, n=6))
N = int(input("Antal summer(flere summer er mere præcist): "))
a = int(input("Integrer fra: "))
b = int(input("Integrer til: "))
# Vi anvender Midpoint metoden til integration og skriver funktionen ind, som skal integreres
def integrate(N, a, b):
def f(x):
return series(math.sqrt(x), x, x0=0, n=6)
value=0
value=2
for n in range(1, N+1):
value += f(a+((n-(1/2))*((b-a)/N)))
value2 = ((b-a)/N)*value
return value2
print("...................")
print("Her er dit svar: ")
print(integrate(N, a, b))
任何人都可以在这里帮助我,非常感谢。
免责声明:我对编程和 Python 还很陌生,如果能提供任何帮助,我将不胜感激。对不起,奇怪的设置,我在写问题时习惯了 LaTeX 和 MathJax :)
解决方案
你得到错误:
TypeError: can't convert expression to float
由于参数按原样传递expr
,math.sqrt(x)
并且sympy
不期望那样。
从更改math.sqrt(x)
为x**0.5
:
print(series(x**0.5, x, x0=0, n=6))
这同样适用于第 16 行。
推荐阅读
- r - R:没有消息的反距离加权插值
- java - 雅加达 JSTL Tomcat
- angular - 使用 Angular 进行单元测试:如何测试父子之间的更改
- javascript - NodeJs 中的 Discord 机器人
- python - 当我尝试创建日志文件时 Heroku /app/[mydir]/[logfile] 上的 FileNotFoundError
- javascript - How should I traverse through a folder of .gifs to display them in a list using Gatsby.js
- node.js - 每次我安装新的 react-app 时依赖关系树中的错误
- python - ModuleNotFoundError("'kafka' 不是一个有效的名称。你的意思是 aiokafka,kafka 之一吗?")
- javascript - 编译时不要运行 linter 和 prettier
- javascript - 用 JavaScript 编码时,什么是 iswgraph() 替代品