Why does `1e500 - 1e500` result in `nan` [duplicate] - python

This question already has an answer here:
What are some possible calculations with numpy or scipy that can return a NaN? [closed]
(1 answer)
Closed 1 year ago.
Not a very important question but I was just curious about the following behavior in Python:
1e500 - 1e500
>>> nan
What is the reasoning for this behavior and why does it not return 0?
I suppose most calculations using 1e500 are pretty weird too but to me at least this 1e500 - 10000 = inf makes sense since the difference would be negligible.
Edit
This question was suggested as holding the answer to my question but in my opinion the answer doesn't explain why this wouldn't be 0, just that it would be NaN.

1e500 is too big to represent in a double precision floating point number, so it turns into inf.
inf-inf gives NaN.

I was thinking of 1e500 as a number, but the real issue is that in Python 1e500 is considered infinity, as it uses whatever floating-point types the underlying platform makes available, which is standard IEEE 754 behavior (Thank you #chpner for that explanation in the comments).
Therefore, the calculation is impossible since infinity - infinity is itself impossible (explained here), which I did not know before.

Related

Rounding in Python with decimal [duplicate]

This question already has answers here:
Rounding error in Python with non-odd number? [duplicate]
(1 answer)
Python 3.x rounding behavior
(13 answers)
Closed 1 year ago.
We all know the rounding issues in Python -- that it's based on float point arithmetic, which is convenient for computers but does not always match practical, human understanding. There's plenty of questions on this on StackOverflow, though most revolve around preserving tiny decimal places, which is different than what I need below.
The solution to these rounding issues is to use the decimal module. Yet, I must be doing something very wrong. Please, consider this, in Octave/Matlab:
>> round(2.5)
ans = 3
>> round(3.5)
ans = 4
The above are the correct results (valid in finance, applied physics, medicine, etc). We know that the same will fail in Python:
>>> round(2.5)
2
>>> round(3.5)
4
No suprise here. But when I use decimal, I still don't receive the correct answer, and here I must be doing something wrong. Starting from the example in https://docs.python.org/3/library/decimal.html:
>>> from decimal import *
>>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
>>> # Round to two places
>>> Decimal('3.214').quantize(TWOPLACES)
Decimal('3.21')
Straightforward, right? But then:
>>> Decimal('3.225').quantize(TWOPLACES)
Decimal('3.22') # Wrong result. Correct would be 3.23
>>> Decimal('3.235').quantize(TWOPLACES)
Decimal('3.24') # Correct result.
So, what can I do to have the correct (as in "real world", "human-based") answer, in a fast, efficient, pythonic manner, and use the result in further computations?
EDIT: I'm using Python 3.7.3.
This happens by design and is not an error.
See answers to this question as to why this happens: Python 3.x rounding behavior
You can set the desired rounding method as a parameter of quantize:
Decimal('3.235').quantize(TWOPLACES, rounding=ROUND_HALF_UP)

Changing the limitation of calculation in Python [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 3 years ago.
I have a question but I do not know what is the relevant part to search or read about.
I would like to calculate some values but Python gives me a rounded value. For example np.exp(3.832781064493026e-31) = 1 but it should not be 1. What is the way of avoiding these approximations? It should be like 1.00000000000000000000000000000384922.
There is mpmath, numpy's multiprecission cousin:
from mpmath import mp
mp.dps = 100
print(mp.exp(3.832781064493026e-31))
# 1.000000000000000000000000000000383278106449302614152558221812007328689735262269801950763925404522797
print(np.expm1(3.832781064493026e-31))
# 3.832781064493026e-31
print(1+np.expm1(3.832781064493026e-31))
# 1.0
# the second term is eaten away by the 64 bit precission (about 16 decimal digits)
Note that mpmath is quite slower than numpy, doesn't work with numpy's arrays and doesn't mix well with other libraries.
Alternatively, especially if you want to calculate exp(x)-1, there is numpy's expm1. This function is introduced because of the precission problems you run into when first calculating exp(x) and then subtracting 1 for small values of x. A better explanation can be found in this post and more thoroughly here.

Mathematics and behavior with floats vs ints [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Why does Python return 0 for simple division calculation?
(6 answers)
Closed 5 years ago.
This is driving me mad... Of all the years I've been using python, this is just now starting to present itself. How I managed to dodge it up until now is beyond me.
If you open a python idle and try this equation...
4/32*100
You'll get '0' as an answer. Now try the same equation using floats....
4.0/32.0*100.0 (or just the first number 4.0/32*100)
You now get an actual percentage.
WTF!?
Is this some kind of python error!? Even a calculation can do the equation and spit out a percentage.
So why can't python see a 4 as 4.0. Better question... What is the interpreter actually seeing if it's not seeing a 4(4.0)?
Someone please clear this up so I can feel professional with python again (lol).
In Python 2, int type division ignores the decimal values of the division.
For example, 1/2 = 0.5, but in int type division, 1/2 will evaluate to 0 because it ignores the decimal values.
Thus, in your case with 4/32*100, 4/32will first evaluate to 0 and then 0*100 will finally equal 0.
On the other hand, in float type division, it will evaluate answers as we would expect (not in a strictly precise definition though, look here for further information).
For Python 2.x, dividing two integers or longs uses integer division, also known as "floor division"(applying the floor function after division)
For Python 3.x, "/" does "true division" for all types.
To make python perform true division, cast any of the denominator for numerator to become float.
float(4)/32*100
or
4/float(32)*100
or doing below to make python 2 division behave like python 3 division
from __future__ import division
4/32*100

Python Rounding Error? [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 5 years ago.
Can someone explain this?
Input:
58/100*100
Result:
57.99999999999999
Yet...
Input:
26/100*100
Result:
26.0
Also, how can I consistently get results like in the second case?
This is all due to floating point arithmetic
and a subtle change in the way python evaluates expressions containing numeric literals.
Since python 3, your expressions above will be calculated in floating point; before then integer arithmetic would have be used.
In IEEE754 floating point, 0.58 is further away from the true value than 0.26. That's enough to throw off the heuristics that your output formatter is using.
Performing the multiplication before the division can help in some circumstances, and will do here as the product can be represented exactly.

Rounding very large numbers in Python (left of the decimal) [duplicate]

This question already has answers here:
round() doesn't seem to be rounding properly
(20 answers)
Closed 6 years ago.
The community reviewed whether to reopen this question 5 months ago and left it closed:
Original close reason(s) were not resolved
The Python round() function will theoretically take negative numbers to round to places left of the decimal. [ I.e. round(150, -2) => 200]
However, it seems to be very susceptible to floating point error.
For example, given a large number say 2e25, it gives weird results.
2e25 === 20000000000000000000000000
But, round(2e25, -23) gives a value like
20000000000000000273942742
When it should just be getting 20000000000000000000000000
I know there's a formatting function, a la this thread:
round() in Python doesn't seem to be rounding properly
However, that only seems to work for rounding to the right of the decimal. Am I wrong? Is there another way to do this? Very frustrating trying to get the math right.
Thanks!
The problem is that 2e25 doesn't actually equal 20000000000000000000000000.
>>> 2e25 == 20000000000000000000000000
False
>>> 2e25 == 20000000000000001811939328
True
The float type doesn't have enough precision to represent such a large integer exactly. Unless you have a good reason for using floating-point values, use integers instead.

Categories

Resources