aroberge / ideas

Easy creation of custom import hooks to experiment on alternatives to Python's syntax; see https://aroberge.github.io/ideas/docs/html/
Other
76 stars 5 forks source link

python as decimal calculator? #48

Closed skirpichev closed 4 months ago

skirpichev commented 4 months ago

Python supports floating point arithmetic of fixed precision (usually something like 53 bits in mantissa). So, "big enough" floating point literals silently truncated:

>>> s = 'x = 3.1111111111111112'
>>> t = ast.parse(s)
>>> v = t.body[0].value
>>> ast.dump(v)
'Constant(value=3.111111111111111)'

But we could recover all digits!

>>> s[v.col_offset:v.end_col_offset]
'3.1111111111111112'

Given this, we could transform arbitrary floating point literals to Decimal instances and then do arithmetic. Similar AST transformation could be useful for arbitrary-precision floating point arithmetic libraries in Python (e.g. mpmath) or CAS (e.g. diofant).

Edit: see https://github.com/diofant/diofant/pull/1378/commits/27ecabc25facf624dbdd4cf18efcb1b85f854dae as an implementation example.

aroberge commented 4 months ago

What's the advantage of this approach over the one illustrated in the following example: https://github.com/aroberge/ideas/blob/master/ideas/examples/decimal_math.py?

skirpichev commented 4 months ago

Sorry, my bad - I miss that example. This indeed looks simpler at the tokenization phase.

skirpichev commented 4 months ago

https://github.com/aroberge/ideas/blob/018fde5d79296431e929c77734060292d0f5d6bb/ideas/examples/decimal_math.py#L23-L24

On another hand, this heuristics not handle all valid float literals, e.g. 1e-10.