Hacker News new | ask | show | jobs
by thanatropism 2349 days ago
Each int also corresponds to a certain real number, but if you write "x*(1/x)==1" for integer x, you'll either

(a) get x casted to a float

(b) get `div` instead (like in Python 2) and obtain a false result

(c) get cursed out with a type error.

These three options are available because it's possible to determine whether a given real number is representable as an int or not. This is not possible with floats.

1 comments

Programming languages aren't able to express arbitrary real numbers, so to "determine whether a given real number is representable as an int or not" is mostly meaningless in a programming language as opposed to a computer algebra system.

What you can do is:

- determine if a float is an integer (trunc(x) == x),

- convert a float to a certain integer type with some kind of rounding, or get an error if it's out of range (see my comment with double_to_uint64),

- convert a float to a certain integer type exactly, or get an error if it's not representable (e.g. by doing both of the above).

The basic reason that so many people fail to use floats correctly is that they act like operations on floats are equivalent to operations on the real numbers they represent, when in fact they are usually defined as the operation on real numbers rounded to a representable value.

> Programming languages aren't able to express arbitrary real numbers,

No system of finite representations is able to express arbitrary real numbers.

Depends what you mean by an arbitrary real number. Any constructed real number could be stored as it’s construction steps. Eg use a series for Pi.

But paradoxically you can store “any” real number, eg the number made up of all future lottery draws.