DEV Community

Shaikhul Islam
Shaikhul Islam

Posted on

TIL:When n + 1 == n in python?

Today I was looking to python docs for doctest and found following

if n+1 == n:  # catch a value like 1e300
    raise OverflowError("n too large")

Immediately I opened the shell and try it:

>>> from math import exp
>>> n = exp(300)
>>> n
1.9424263952412558e+130
>>> n + 1 == n
True

TIL n+1 == n! and how to guard against a ridiculously large number

Top comments (3)

Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

That's a fairly awful way to handle floating point limits. Much lower ranges should be checked if the algorithm is in danger of breaking.

Collapse
 
abdurrahmaanj profile image
Abdur-Rahmaan Janhangeer

That's an oft-forgotten error when exposing to remote commands as it is too innocent.

Collapse
 
itr13 profile image
Mikael Klages • Edited

If you need numbers that might get that high, maybe pure integer calculations would work.

There's also some arbitrary precision float modules you could use.