python - 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:
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:
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 :/
推荐阅读
- .net - .NET Core WebApi CSV 文件解析和存储在数据库中
- c# - 在运行时使用本机依赖项(和其他文件/文件夹)加载程序集
- spring-boot - Intellij Hot Reload 重新加载后无法正常工作它无法找到 spring 注入的 bean
- java - 如何使用 Map 键作为列表对象和值作为顺序对 ArrayList 进行排序?
- php - 将 PHP 表单数据发送到不同的页面
- python - 'Nonetype' 不可调用
- flutter - 当我在有状态中使用时,颤振图像总是重新加载
- react-native - AsyncStorage 在 React-Native 中有奇怪的字符
- react-native - 如何获得 Base64 输出?
- symfony - 您一般如何解释有序地图?