Nim: stdlib needs ryu for compact and performant float to string

Created on 8 Feb 2020  路  2Comments  路  Source: nim-lang/Nim

as of https://github.com/nim-lang/Nim/pull/13364 json works with roundtrip correctness in mind, but sacrifices shortness of representation.
python's json doesnt' have this issue.

Example

import std/json
echo(%* 0.6) # 0.59999999999999998

Current Output

0.59999999999999998

Expected Output

0.6

Possible Solution

port/wrap/implement ryu https://github.com/ulfjack/ryu which has several benefits:

  • speed
  • compactness

Ryu generates the shortest decimal representation of a floating point number that maintains round-trip safety. That is, a correct parser can recover the exact original number. For example, consider the binary 32-bit floating point number 00111110100110011001100110011010. The stored value is exactly 0.300000011920928955078125. However, this floating point number is also the closest number to the decimal number 0.3, so that is what Ryu outputs.

example: python's print wrt float:

as a nice-to-have, we can also have echo behave same as in python:

  a = 0.1
  import numpy
  for i in range(0,10):
    print(a)
    a = numpy.nextafter(a, float('Inf'))

```
0.1
0.10000000000000002
0.10000000000000003
0.10000000000000005
0.10000000000000006
0.10000000000000007
0.10000000000000009
0.1000000000000001
0.10000000000000012
0.10000000000000013

this isn't the case currently in nim
```nim
  var a = 1.0
  for i in 0..<10:
    echo a
    a = nextafter(a, Inf)
1.0
1.0
1.0
1.000000000000001
1.000000000000001
1.000000000000001
1.000000000000001
1.000000000000002
1.000000000000002
1.000000000000002

links

Feature Stdlib

Most helpful comment

Decided to do a syntax port and then once the tests pass and we can benchmark it, we can twiddle the bits and make it our own.

https://github.com/disruptek/ryu

All 2 comments

I said I'd do it and I will. :laugh: Do you need it soon?

Decided to do a syntax port and then once the tests pass and we can benchmark it, we can twiddle the bits and make it our own.

https://github.com/disruptek/ryu

Was this page helpful?
0 / 5 - 0 ratings

Related issues

capocasa picture capocasa  路  3Comments

alaviss picture alaviss  路  3Comments

zzz125 picture zzz125  路  4Comments

zaxebo1 picture zaxebo1  路  4Comments

teroz picture teroz  路  3Comments