Skip to content
Advertisement

How could the energy and cos function be in different shapes?

I am trying to write a code that calculates an integral from zero to pi. But it gives an error which I do not understand how to fix. Thank you for your time.

import numpy as np
from math import pi,cos
vtheta=np.linspace(0.0,pi,1000)
def my_function(x):
    Energy = np.arange(2.1,300.1,0.1)
    return ((1.0)/(Energy-1+np.cos(x)))
print (my_function(vtheta).sum())

Advertisement

Answer

As is pointed out in the top comment: Energy.shape == (2980,), but x.shape == (1000,) so reduce the number of elements in Energy or increase np.cos(x). Since energy is just a numpy arrage i reduced it to size=1000.

In order to fix this they need to be the same size, so this ,for example, works:

import numpy as np
from math import pi,cos
vtheta=np.linspace(0.0,pi,1000)
def my_function(x):
    Energy = np.arange(2.1,102.1,0.1)    #<-- changed 300.1 to 102.1
    return ((1.0)/(Energy-1+np.cos(x)))
print (my_function(vtheta).sum())

This is the result (with the above):

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