[英]My function does not take floats: - “TypeError('only size-1 arrays can be converted to Python scalars')” (I think it has a quick fix!)
I wrote a code to use Riemann to calculate the area under certain function. 我编写了一个代码,使用黎曼来计算某些功能下的面积。 It works well but when I set the boundaries to decimal number I get an error. 它工作正常,但是当我将边界设置为十进制数时,会出现错误。 I think I should tell the function I want to be able to enter floats but I don't see how. 我想我应该告诉该函数我希望能够输入浮点数,但我不知道如何。 I think it is an easy fix, hope someone can help me: 我认为这很容易解决,希望有人可以帮助我:
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)
Got the followin output and no error found: 得到了Followin输出,没有发现错误:
Midpoint Riemann Sum: 0.3333333325
Midpoint Riemann Sum: 0.527737838955
Midpoint Riemann Sum: 0.459697694323
Midpoint Riemann Sum: 0.310268301273
What can we do to reproduce the error ? 我们该怎么做才能重现错误?
EDIT: 编辑:
using a and b as decimals: 使用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)
OUTPUT: 输出:
Midpoint Riemann Sum: 9.66243875102
Midpoint Riemann Sum: 27.9239376537
Midpoint Riemann Sum: 1.87259837142
Midpoint Riemann Sum: 0.724064617658
and still got no error :/ 仍然没有错误:/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.