我这里有一个脚本,它调用一个自定义函数并在for循环中运行它。该函数用于查找函数的根,这里定义为f(X)
,并使用容差值拒绝任何假根。问题是,我一直收到错误:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-17-10016a66492e> in <module>
17 start = tictoc()
18 for i in range(0,n):
---> 19 fsolvetol(f,x0,q,i,tol)
20 finish = tictoc() - start
21 print('Elapsed time is {0} seconds'.format(finish))
~\OneDrive - University of Massachusetts Dartmouth\EAS520\Project1\hw3\customsolver.py in fsolvetol(func, guesses, roots, i, Tol)
7 def fsolvetol(func,guesses,roots,i,Tol):
8 import numpy as np
----> 9 roots[i] = fsolve(func,guesses[i])
10 # if func(roots[i]) > Tol or func(roots[i]) < -Tol:
11 # roots[i] = 1
NameError: name 'np' is not defined
尽管在我的两个脚本中都将numpy定义为np。下面是我的主脚本和自定义函数。
#!/usr/bin/env python3
import numpy as np
from numpy import pi
from time import perf_counter as tictoc
from customsolver import *
import matplotlib.pyplot as plt
# Organizing Inputs #
def f(x): return np.sin(3*pi*np.cos(2*pi*x)*np.sin(pi*x))
a = -3; b = 5; n = 4**4
x0 = np.linspace(a,b,n)
q = np.zeros(np.shape(x0))
tol = 10**(-13)
#####################
start = tictoc()
for i in range(0,n):
fsolvetol(f,x0,q,i,tol)
finish = tictoc() - start
print('Elapsed time is {0} seconds'.format(finish))
# Processing Outputs #
q = np.unique(q) # keep roots with unique values only.
q = q[~np.isnan(q)] # removes the nan value
我调用此处编写的自定义函数,如下所示:
#!/usr/bin/env python3
from scipy.optimize import fsolve
import numpy as np
# Flags points that fsolve incorrectly assigns as roots within tolerance (now a function!)
def fsolvetol(func,guesses,roots,i,Tol):
roots[i] = fsolve(func,guesses[i])
if func(roots[i]) > Tol or func(roots[i]) < -Tol:
roots[i] = np.nan
if __name__ == "__main__":
fsolvetol()
尽管
发布于 2021-10-17 05:19:29
你忘了加np了。在你的根目录前面,它应该是np.rootsi。或者您可以导入根目录
from scipy.optimize import fsolve
import numpy as np
from numpy import roots // Just do this and it should be fine
# Flags points that fsolve incorrectly assigns as roots within tolerance (now a function!)
def fsolvetol(func,guesses,roots,i,Tol):
roots[i] = fsolve(func,guesses[i])
if func(roots[i]) > Tol or func(roots[i]) < -Tol:
roots[i] = np.nan
if __name__ == "__main__":
fsolvetol()
https://stackoverflow.com/questions/69601365
复制相似问题