3 ms·
"You could return 23.5 in the former case, but then you'd no longer have an Integer." This works rather well in Python. >>> a = 10 >>> b = 1.1 >>>
by BerislavLopac 9y ago
"You could return 23.5 in the former case, but then you'd no longer have an Integer."
This works rather well in Python.
>>> a = 10
>>> b = 1.1
>>> c = a + b
>>> type(a)
<class 'int'>
>>> type(b)
<class 'float'>
>>> type(c)
<class 'float'>
- sillysaurus3 9y agoThere's a solution to all of this: TAoCP has thought through these issues carefully, and it would probably be best to study the tradeoffs Knuth presented. Python handles common cases, but it breaks when you push it too far: >>> 1e100 1e+100 >>> 1e100+0.1 1e+100 >>> 1e100+0.1 == 1e100 True >>> 9007199254740992 + 0.5 9007199254740992.0 >>> 9007199254740992 + 0.5 == 9007199254740992 True >>> 9007199254740992 + 0.5 + 1 9007199254740992.0 >>> x = 9007199254740992 >>> y = x >>> y += 1 >>> x == y False >>> x = 9007199254740992 + 0.5 >>> y = x >>> x += 1 >>> x == y True You could argue that handling the common cases is all that's needed, but stuff like this pops up in e.g. writing software rasterizers. It might also be one reason why PyPy can't quite match the speed of native programs, though that's just a guess.
- orf 9y agoYou're right about those Python cases (and they are surprising!). But if you're dealing with numbers those big and adding decimals you would want to use the Decimal module: >> from decimal import Decimal as D >> 9007199254740991 + D('0.1') > Decimal('9007199254740991.1')
- SamReidHughes 9y agoIt wouldn't work well in JavaScript because it already has double-precision floats as its datatype used for both integers and floats. Python doesn't have floats getting used as integers, which is what leads to this problem.