Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy arange: how to make "precise" array of floats?

In short, the problem I encounter is this:

aa = np.arange(-1., 0.001, 0.01)
aa[-1]
Out[16]: 8.8817841970012523e-16

In reality, this cause a series problem since my simulations doesn't allow positive value inputs.

I can sort of get around by doing:

aa = np.arange(-100, 1, 1)/100.
aa[-1]
Out[21]: 0.0

But this is a pain. Practically you can't do this every time.

This seems like such a basic problem. There's gotta be something I am missing here. By the way, I am using Python 2.7.13.

like image 667
Alex Avatar asked Nov 11 '17 21:11

Alex


People also ask

What is the difference between the standard range () function and NumPy's arange () function?

The main difference between the two is that range is a built-in Python class, while arange() is a function that belongs to a third-party library (NumPy). In addition, their purposes are different! Generally, range is more suitable when you need to iterate using the Python for loop.

What is the difference between NumPy Linspace and arange?

The essential difference between NumPy linspace and NumPy arange is that linspace enables you to control the precise end value, whereas arange gives you more direct control over the increments between values in the sequence.

Is NumPy arange faster than range?

This is because the arange() takes much lesser memory than that of the built-in range() function. The range function is considerably slower as it generates a range object just like a generator. It takes more memory space when dealing with large sized Python objects.


1 Answers

Using np.linespace solved it for me:

For example np.linspace(0.5, 0.9, 5) produce [0.5 0.6 0.7 0.8 0.9].

like image 200
Edo Wexler Avatar answered Oct 22 '22 06:10

Edo Wexler