-1

Here is my code:

y = np.array([-3.44 , 1.16 , -0.81])
y = np.exp(y)
print(y)

for this block, I got the below result

[0.03206469 3.18993328 0.44485807]

However, when I add 3.91 to the list, the result changed

x = np.array([-3.44 , 1.16 , -0.81 , 3.91])
x = np.exp(x)
print(x)

result:

[3.20646853e-02 3.18993328e+00 4.44858066e-01 4.98989520e+01]

how can I prevent this change?

Barmar
  • 741,623
  • 53
  • 500
  • 612
alifallahi
  • 332
  • 1
  • 9

1 Answers1

2

You can use np.set_printoptions:

>>> x = np.array([-3.44 , 1.16 , -0.81 , 3.91])
>>> x = np.exp(x)
>>> print(x)
[3.20646853e-02 3.18993328e+00 4.44858066e-01 4.98989520e+01]

>>> np.set_printoptions(suppress=True, precision=8)

>>> print(x)
[ 0.03206469  3.18993328  0.44485807 49.89895197]

Explanation:

Decimal rounding can not always be exactly represented in binary, so you will see some floating point inconsistencies. For example:

>>> 0.1 + 0.2
0.30000000000000004

In light of these inconsistencies, numpy by default represents floating points in scientific notation. The way I have shown above, only sets the printing option to the way you desire, but the actual representation inside the array does not change.

np.set_printoptions(suppress=True) suppresses the scientific notation, and suppresses the floating points to 8 decimal places by default, so technically the precision parameter was not needed in this case:

>>> np.set_printoptions(suppress=True)
>>> x
[ 0.03206469  3.18993328  0.44485807 49.89895197]

I added precision just in case you want a desired precision while printing.

>>> np.set_printoptions(suppress=True, precision=2)
>>> x
array([ 0.03,  3.19,  0.44, 49.9 ])

Learn more about floating point operations here:

  1. Is floating point math broken?

  2. https://0.30000000000000004.com/

Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52