top | item 45441035

(no title)

mbrameld | 5 months ago

I might be wrong, but I was under the impression that result is platform-dependent?

https://docs.python.org/3/tutorial/floatingpoint.html#floati...

discuss

order

eesmith|5 months ago

Raku represents 0.1, 0.2, and 0.3 internally as rational numbers. https://docs.raku.org/type/Rat. 1/10 + 1/5 == 3/10

Note that "On overflow of the denominator during an arithmetic operation a Num (floating-point number) is returned instead." A Num is an IEEE 754 float64 ("On most platforms" says https://docs.raku.org/type/Num)

Python always uses IEEE 754 float64, also on most platforms. (I don't know of any Python implementation was does otherwise.) If you want rationals you need the fractions module.

  >>> from fractions import Fraction as F
  >>> F("0.1") + F("0.2") == F("0.3")
  True
  >>> 0.1 + 0.2 == 0.3
  False
This corresponds to Raku's FatRat, https://docs.raku.org/type/FatRat. ("unlike Rat, FatRat arithmetics do not fall back Num at some point, there is a risk that repeated arithmetic operations generate pathologically large numerators and denominators")

librasteve|5 months ago

good explanation

that said, decimals (eg 0.1) are in fact fractions, and the subtlety that 0.1 decimal cannot be precisely represented by a binary floating point number in the FPU is ignored by most languages where the core math is either integer or P754

bringing Rational numbers in as a first class citizen is a nice touch for mathematicians, scientists and so on

another way to look at it for Raku is that

  Int → integers (ℤ)
  Rat → rationals (ℚ)
  Num → reals (ℝ)