gpt4 book ai didi

Python 无法从 phi 创建 mpf

转载 作者:行者123 更新时间:2023-11-28 16:46:35 28 4
gpt4 key购买 nike

在修复上一个问题 (Python AttributeError:cos) 中的导入并使用 sympy 函数稍作更改后:

from sympy import *
from sympy import Symbol
from sympy.solvers import nsolve

# Symbols
theta = Symbol('theta')
phi = Symbol('phi')
phi0 = Symbol('phi0')
H0 = Symbol('H0')
# Constants
a = 0.05
b = 0.05**2/(8*pi*1e-7)
c = 0.001/(4*pi*1e-7)
phi0 = 60*pi/180
H0 = -0.03/(4*pi*1e-7)
def m(theta,phi):
return Matrix([[sin(theta)*cos(phi), sin(theta)*cos(phi), cos(phi)]])
def h(phi0):
return Matrix([[cos(phi0), sin(phi0), 0]])
def k(theta,phi,phi0):
return m(theta,phi).dot(h(phi0))
def F(theta,phi,phi0,H0):
return -(a*H0)*k(theta,phi,phi0)+b*(cos(theta)**2)+c*(sin(2*theta)**2)+sin(theta)**4*sin(2*phi)**2
def F_phi(theta,phi,phi0,H0):
return simplify(diff(F(theta,phi,phi0,H0),phi))
def G(phi):
return F_phi(pi/2,phi,phi0,H0)
solution = nsolve(G(phi), phi)
print solution

我得到这个回溯:

Traceback (most recent call last):
File "Test.py", line 31, in <module>
solution = nsolve(G(phi), phi)
File "/usr/lib64/python2.7/site-packages/sympy/solvers/solvers.py", line 2050, in nsolve
return findroot(f, x0, **kwargs)
File "/usr/lib64/python2.7/site-packages/mpmath/calculus/optimization.py", line 908, in findroot
x0 = [ctx.convert(x0)]
File "/usr/lib64/python2.7/site-packages/mpmath/ctx_mp_python.py", line 662, in convert
return ctx._convert_fallback(x, strings)
File "/usr/lib64/python2.7/site-packages/mpmath/ctx_mp.py", line 561, in _convert_fallback
raise TypeError("cannot create mpf from " + repr(x))
TypeError: cannot create mpf from phi

最佳答案

nsolve 的第二个参数应该是初始猜测,而不是符号。来自文档字符串

Solve a nonlinear equation system numerically::

nsolve(f, [args,] x0, modules=['mpmath'], **kwargs)

f is a vector function of symbolic expressions representing the system.
args are the variables. If there is only one variable, this argument can
be omitted.
x0 is a starting vector close to a solution.

所以你想要类似 nsolve(G(phi), 0)nsolve(G(phi), 3) 等的东西(取决于你的解决方案想要)。

关于Python 无法从 phi 创建 mpf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13337346/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com