0

I am trying to truncate (by two decimal places) an array of floats in a numpy array. I do this by doing the following to each element:

np.trunc(100 * i) / 100

However, due to some floating point problems in python, sometimes this formula above does not work. Take for example -2.01 * 100 = -200.99999999999997. Thus, the np.trunc(100 * -2.01) / 100 will not work. it will output -2.00.

Is there a better way to truncate two decimal places in python using np.trunc? Without np.trunc?

Thank you!

Peabrain
  • 519
  • 2
  • 12
  • Disclaimer here. I don't want to convert it into a string and do string manipulations. – Peabrain Sep 15 '20 at 23:27
  • 1
    Don't use binary. The result you are getting is the closest binary representation of 2.01 that is possible. Use a rational number instead. – Mad Physicist Sep 15 '20 at 23:28
  • Try this: `x = 2.01; print(f'{x:0.16f})'` – Mad Physicist Sep 15 '20 at 23:29
  • I'm not aware that I was even using binary. How did you know I was? And how do I use rational numbers instead? – Peabrain Sep 15 '20 at 23:30
  • Store the numerator and denominator. So if you want a multiple of 100, just store the integer part. Print it as `f'{x//100}.{x%100}'`. If you want to rephrase your question to include that as a posisiblity, I can post an answer. – Mad Physicist Sep 15 '20 at 23:31
  • @MadPhysicist, the result of the print will be: 2.0099999999999998. Still will be a problem on truncation. I would have to round? – Peabrain Sep 15 '20 at 23:31
  • The built-in `float` types use binary by design. For rational numbers, look up the [fractions](https://docs.python.org/3/library/fractions.html) class. – Prune Sep 15 '20 at 23:31
  • @Prune. You really don't need to. Just store it as an integer. The denominator is fixed. – Mad Physicist Sep 15 '20 at 23:32
  • @Peabrain. Before proceeding, please read the duplicate very very carefully. Also, check out the page https://en.wikipedia.org/wiki/IEEE_754#Representation_and_encoding_in_memory – Mad Physicist Sep 15 '20 at 23:33

0 Answers0