Example NumPy Floats

Can you help with with this please: Create a NumPy programme to generate all floats with a step of 0.5 between 0 and 15.

Please post this in #users. This category is for discussing how to distribute Python projects.

You need to write code before asking for help.

You can add 0.5 to 0.0 while the result has not become larger than 15.
A first attempt can be

result = []
first = 0.0
last = 15.0
increment = 0.5
while current_value <= last:
  result.append(current_value)
  current_value += increment

Since we can predict how many values we will get, namely int((15 - 0.0) / 0.5) + 1 we could also do

first = 0.0
last = 15.0
increment = 0.5
result = [first + n * increment for n in range(int((last - first)/increment) + 1)]

Note that 0.5 =2^{-1} and 0.0 are sums of powers of 2. So, all the values that we need are values that float can take. If they had given other value instead of 0.5 perhaps the values that we need are not values that float can take. So, we have to compute them approximatively. The first approach of doing current_value += increment can magnify the error in that case. So, it might be better to use the first + n * increment approach.

To be honest, numpy already as something built-in that can do this:

>>> list(np.arange(0.0, 15.5, 0.5))
[0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0, 10.5, 11.0, 11.5, 12.0, 12.5, 13.0, 13.5, 14.0, 14.5, 15.0]

But that may be cheating if it’s an assignment :upside_down_face:.

It is a numpy program, and clearly the most sensible one. A more sensible exercise would be to do the program in python without numpy.

Trying to answer questions about class assignments is often frustrating, especially when no code is given, because context is lacking.

1 Like