我的函数不使用浮点数:- "TypeError('only size-1 arrays can be converted to Python scalars')"(我认为它有一个快速修复!)
My function does not take floats: - "TypeError('only size-1 arrays can be converted to Python scalars')" (I think it has a quick fix!)
我写了一段代码,在某个函数下用黎曼计算面积。它运行良好,但是当我将边界设置为十进制数时,出现错误。我想我应该告诉函数我希望能够输入浮点数,但我不知道该怎么做。我认为这是一个简单的解决方法,希望有人能帮助我:
import numpy as np
import math
def func(x):
return x ** 2
def func1(x):
return x ** (x +0.5)
def func2(x):
return np.sin(x)
def func3(x):
return np.sin(x ** 2)
def riemann(f,a,b,N):
dx = (b-a)/N
x_midpoint = np.linspace(dx/2,b - dx/2,N)
riemann_sum = np.sum(f(x_midpoint) * dx)
return riemann_sum
res = riemann(func,0,1,10000)
res1 = riemann(func1,0,1,10000)
res2 = riemann(func2,0,1,10000)
res3 = riemann(func3,0,1,10000)
print("Midpoint Riemann Sum:",res)
print("Midpoint Riemann Sum:",res1)
print("Midpoint Riemann Sum:",res2)
print("Midpoint Riemann Sum:",res3)
得到以下输出并且没有发现错误:
Midpoint Riemann Sum: 0.3333333325
Midpoint Riemann Sum: 0.527737838955
Midpoint Riemann Sum: 0.459697694323
Midpoint Riemann Sum: 0.310268301273
我们如何重现错误?
编辑:
使用 a 和 b 作为小数:
res = riemann(func,0.2,3.14,10000)
res1 = riemann(func1,0.2,3.14,10000)
res2 = riemann(func2,0.2,3.14,10000)
res3 = riemann(func3,0.2,3.14,10000)
输出:
Midpoint Riemann Sum: 9.66243875102
Midpoint Riemann Sum: 27.9239376537
Midpoint Riemann Sum: 1.87259837142
Midpoint Riemann Sum: 0.724064617658
仍然没有错误:/
我写了一段代码,在某个函数下用黎曼计算面积。它运行良好,但是当我将边界设置为十进制数时,出现错误。我想我应该告诉函数我希望能够输入浮点数,但我不知道该怎么做。我认为这是一个简单的解决方法,希望有人能帮助我:
import numpy as np
import math
def func(x):
return x ** 2
def func1(x):
return x ** (x +0.5)
def func2(x):
return np.sin(x)
def func3(x):
return np.sin(x ** 2)
def riemann(f,a,b,N):
dx = (b-a)/N
x_midpoint = np.linspace(dx/2,b - dx/2,N)
riemann_sum = np.sum(f(x_midpoint) * dx)
return riemann_sum
res = riemann(func,0,1,10000)
res1 = riemann(func1,0,1,10000)
res2 = riemann(func2,0,1,10000)
res3 = riemann(func3,0,1,10000)
print("Midpoint Riemann Sum:",res)
print("Midpoint Riemann Sum:",res1)
print("Midpoint Riemann Sum:",res2)
print("Midpoint Riemann Sum:",res3)
得到以下输出并且没有发现错误:
Midpoint Riemann Sum: 0.3333333325
Midpoint Riemann Sum: 0.527737838955
Midpoint Riemann Sum: 0.459697694323
Midpoint Riemann Sum: 0.310268301273
我们如何重现错误?
编辑:
使用 a 和 b 作为小数:
res = riemann(func,0.2,3.14,10000)
res1 = riemann(func1,0.2,3.14,10000)
res2 = riemann(func2,0.2,3.14,10000)
res3 = riemann(func3,0.2,3.14,10000)
输出:
Midpoint Riemann Sum: 9.66243875102
Midpoint Riemann Sum: 27.9239376537
Midpoint Riemann Sum: 1.87259837142
Midpoint Riemann Sum: 0.724064617658
仍然没有错误:/