首页 > 解决方案 > 我将一组 N 值传递给一个循环,但无法让它打印输出

问题描述

当我将数字传递给函数时,我似乎无法获得输出。我需要得到计算值并从精确值中减去它。有什么我做错了吗?

def f1(x):
  f1 = np.exp(x)
  return f1;
def trapezoid(f,a,b,n):
   '''Computes the integral of functions using the trapezoid rule
   f = function of x
   a = upper limit of the function
   b = lower limit of the function
   N = number of divisions'''
   h   = (b-a)/N
   xi  = np.linspace(a,b,N+1)
   fi  = f(xi)
   s   = 0.0
   for i in range(1,N):
       s = s + fi[i]
   s = np.array((h/2)*(fi[0] + fi[N]) + h*s)
   print(s)
   return s
exactValue = np.full((20),math.exp(1)-1)
a  = 0.0;b = 1.0  # integration interval [a,b]
computed = np.empty(20)
E=np.zeros(20)
exact=np.zeros(20)
N=20
def convergence_tests(f, a, b, N):
 n = np.zeros(N, 1);
 E = np.zeros(N, 1);
 Exact = math.exp(1)-1
 for i in range(N):
   n[i] = 2^i
   computed[i] = trapezoid(f, a, b, n[i])
   E = abs(Exact - computed)
 print(E, computed)
 return E, computed 

标签: pythonloopsnumpyerror-handling

解决方案


你已经定义了几个函数,但是你的主程序从不调用它们中的任何一个。事实上,你的“父”函数convergence_test 不能被调用,因为它是在程序底部定义的。

我建议你使用增量编程:写几行;在继续代码中的下一个小任务之前测试它们。在帖子中,您已经编写了大约 30 行活动代码,但没有意识到实际上没有任何代码真正执行。这可能还有其他几个错误;您可能很难修复所有这些以获得预期的输出。

从小处着手,逐步成长。


推荐阅读