# Weird floating point vs rational behavior

**URL:** <https://discourse.julialang.org/t/weird-floating-point-vs-rational-behavior/96466>\
**Category:** General Usage\
**Tags:** numerics, rationals, float\
**Created:** [March 22, 2023, 5:37pm UTC](https://discourse.julialang.org/t/weird-floating-point-vs-rational-behavior/96466 "2023-03-22T17:37:52Z")\
**Posts on this page:** 1\
**Showing post:** 7

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [March 23, 2023, 12:28pm UTC](https://discourse.julialang.org/t/weird-floating-point-vs-rational-behavior/96466/7 "2023-03-23T12:28:54Z")

</div>

> [@albheim](#):
>
> I’m also a bit curious what the printing is actually based on, is it just picking the shortest representation that is closer to the actual value than the neighbouring float values, or what is the rule for printing?

For `Float64/32/16`, it’s printing the _shortest_ decimal value that _rounds to the same value_ (when rounded to the nearest binary floating point number).

In particular, it uses a state-of-the-art algorithm called [Ryū](https://dl.acm.org/doi/10.1145/3192366.3192369). (Previously it used another algorithm called Grisu that did the same thing.) In particular, as described in the Ryū paper, the criteria for display are:

 ![image](https://global.discourse-cdn.com/julialang/original/3X/e/a/ea9a5d2368594136862f8180b796202a186899a8.png)

as laid out in a [classic 1990 paper](https://dl.acm.org/doi/10.1145/989393.989431).

See also these posts:

- [Working with machine precision - #9 by kristoffer.carlsson](https://discourse.julialang.org/t/working-with-machine-precision/29576/9)
- [Are BigFloats unable to exactly represent 0.1? - #6 by Sukera](https://discourse.julialang.org/t/are-bigfloats-unable-to-exactly-represent-0-1/62192/6)
- [Sum of float64 vector gives slightly incorrect answer - #20 by stevengj](https://discourse.julialang.org/t/sum-of-float64-vector-gives-slightly-incorrect-answer/8577/20)

and many others… (Note, however, that `BigFloat` printing uses a separate algorithm implemented in the GNU MPFR library, and IIRC it is _not_ always the shortest decimal representation.)

---

_[View the full topic](https://discourse.julialang.org/t/weird-floating-point-vs-rational-behavior/96466)._
