-1

I want to create an array of numbers from -Pi to +Pi with a step size of Pi/4. However, using linspace does not give me the accuracy I want, I am guessing it's a problem with the data type.

arr = np.linspace(-math.pi,math.pi,math.pi/4)
print(math.cos(arr[2]))

This does not output zero but outputs an extremely small number. How do I fix the data type so that I get the output as zero?

Tanmay Bhore
  • 89
  • 2
  • 9

2 Answers2

1

The last parameter into np.linspace is the number of samples, not the size of them. In your case, you want 9 samples.

arr = np.linspace(-math.pi,math.pi,9)
print(arr)

Output:

[-3.14159265 -2.35619449 -1.57079633 -0.78539816  0.          0.78539816
  1.57079633  2.35619449  3.14159265]

To explain why you are not getting exactly zero at -pi/2, see this post.

The number π cannot be represented exactly as a floating-point number.

cwalvoort
  • 1,851
  • 1
  • 18
  • 19
0

You should be using the numpy arange function:

import math
import numpy as np
arr = np.arange(-math.pi,math.pi,math.pi/4) #replace pi with 5/4*pi to include pi as endpoint
print(math.cos(arr[2]))
Vikhyat Agarwal
  • 1,723
  • 1
  • 11
  • 29
  • Note that `arange` **excludes** the end `math.pi`, while `linspace` **includes** it, unless specified otherwise. Of course `linspace` expects number of samples, not step size, as mentioned. – Jan Christoph Terasa Jun 10 '19 at 18:12