我这里有一个脚本,它调用一个自定义函数并在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()
尽管
你忘了添加np。在你的根[i]前面,它应该是np.根[i]。或者你可以导入根
相关问题 更多 >
编程相关推荐