Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is the np.sin function bugged?

Minimal example:

import numpy as np
import matplotlib.pyplot as plt

x_ = np.arange(2000)

frequency = 2 * np.pi
sine = np.sin(x_*frequency)
plt.plot(x_, sine)
plt.show()

produces following plot:
enter image description here

The multiplication np.sin(x_*frequency) results in very confusing behavior. How can the output of the sine function be smaller than -1 and showing multiple amplitudes?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If np.sin(x_/frequency) than it shows the expected behavior:enter image description here

>Solution :

You think you’re drawing a continuous function, but all the points in vector x_ are of the form (integer) * 2 pi. And the sin of a multiple of 2pi is 0.

So the points you’re giving to plt.plot are only points where the sin is 0.

They are not exactly 0, because np.pi is not exactly pi, and you’re multiplying that error by up to 2000.

What you’re observing is that the error on np.sin(2000 * 2 * np.pi) is on the order of 1e-12, or 0.000000000001 if you prefer that notation.

If you want to observe a curve that looks more like the curve of sin, try including non-integers in vector x:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,10,1000) # 1000 points in interval [0, 10]
y = np.sin(x * 2 * np.pi)

plt.plot(x,y)

y=sin(x)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading