Skip to content
Advertisement

TypeError: only size-1 arrays can be converted to Python scalars when using trapz method

This is my python code

import numpy as np
from scipy.integrate import quad, trapz, simps
import math

def f(x):
    return math.exp(-(x**2/2))/math.sqrt(2*math.pi)

result, error = quad(f, 0, np.inf)
print("{:f} {:g}".format(result, error))

x = np.arange(0, 99999, 0.001)

fun = f(x)

res1 = trapz(fun, x)
print(res1)

And am getting this error:

... line 6, in f
return math.exp(-(x**2/2))/math.sqrt(2*math.pi)
TypeError: only size-1 arrays can be converted to Python scalars

Why is that so? Integration using quad method worked fine but not with trapz method

Advertisement

Answer

As a user commented, you can only use math functions with scalar values, for arrays you have to use math functions provided in NumPy library.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement