Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are the programming languages limits precision of 22/7 equally?

I tried

Erlang
$ erl
1> Pi = 22/7.
3.142857142857143

Haskell
$ ghci 
Prelude> 22/7
3.142857142857143

Python
$ python
>>> 22/7.0
3.142857142857143

Ruby 
$ irb
2.1.6 :001 > 22 / 7.0
 => 3.142857142857143

The results are the same. Why?

like image 999
CodeGroover Avatar asked Dec 04 '22 03:12

CodeGroover


1 Answers

This happens because all the languages are using the same numerical representation for non-integer numbers: IEEE 754 floating point numbers with, most likely, the same level of precision. (Either 32-bit "floats" or 64-bit "doubles", depending on how your system and languages are configured.)

Floating point numbers are the default choice for this sort of operation, in large part because they're supported directly in hardware. However, fundamentally, nothing stops languages from supporting other kinds of numbers as well. This is easiest to demonstrate in Haskell, which has rational numbers in its standard library:

λ> 22/7 :: Rational
22 % 7

A rational number is a fraction, so it's stored as a pair of integers and you don't lose any precision when dividing. At the same time, some operations are more difficult and less efficient than with normal floating point numbers.

Another possible representation are fixed-point numbers which have a smaller range than floating point numbers but do a better job of maintaining precision within that range. (I'm really handwaving a lot of details here.) You can try these out in Haskell too:

λ> import Data.Fixed
λ> 22/7 :: Deci
3.1
λ> 22/7 :: Centi
3.14
λ> 22/7 :: Micro
3.142857
like image 53
Tikhon Jelvis Avatar answered Jan 08 '23 10:01

Tikhon Jelvis