-2

I'm certainly a newbie to Python. Hence, I'm struggling to understand the results that the following bit of code gives me for i = 15 and i = 21. In all other cases is does what I expect.

import numpy as np

i_values = []
results = []
results2 = []

for i in range(27):
  i_values.append(i)
  result = np.int((i*0.02+0.03)*1.e2)
  results.append(result)

  result2 = (i*0.02+0.03)*1.e2
  results2.append(result2)

print i_values
print results
print results2

My question is: Why is the code working for most numbers but fails for certain values of i? I could solve the problem by

result = np.int(np.rint(((i*0.02+0.03)*1.e2))

but I just want to understand why it occurs in the first place.

Thank you in advance.

J. Hund
  • 3
  • 1
  • 2
    What do you mean by "fail"? Which numbers, and what is the output for those numbers? – Useless Feb 20 '18 at 11:03
  • You can see that for 15 you get 32.9999 and for 21 you get 44.9999. `np.int()` keeps only the integer part, but `np.rint()` rounds to closest integer. As for why the answer is 32.9999, it has do with how floating numbers work and it has been answered before. – Reti43 Feb 20 '18 at 11:08

1 Answers1

0

I think this link should give you an insight:

Why Are Floating Point Numbers Inaccurate?

It is understandable since the results can be slightly different due to precision if compared between how different languages deal with them. A quick example between using in python and just googling the answer:

Python example

Google example

Chicrala
  • 994
  • 12
  • 23