Bug #16843
closedA bug with floating point multiplication
Description
I've reproduced it with both currently stable versions: 2.6.6 and 2.7.1.
irb(main):001:0> 0.29 * 100
=> 28.999999999999996
irb(main):002:0> 0.29 * 100.0
=> 28.999999999999996
irb(main):003:0> 0.28 * 100
=> 28.000000000000004
irb(main):004:0> 0.28 * 100.0
=> 28.000000000000004
irb(main):005:0> 0.27 * 100.0
=> 27.0
irb(main):006:0> 0.27 * 100
=> 27.0
$ ruby -v
ruby 2.7.1p83 (2020-03-31 revision a0c7c23c9c) [x86_64-linux]
irb(main):001:0> 0.29 * 100
=> 28.999999999999996
irb(main):002:0> 0.29 * 100.0
=> 28.999999999999996
irb(main):003:0> 0.28 * 100.0
=> 28.000000000000004
irb(main):004:0> 0.28 * 100
=> 28.000000000000004
irb(main):005:0> 0.27 * 100
=> 27.0
irb(main):006:0> 0.27 * 100.0
=> 27.0
$ ruby -v
ruby 2.6.6p146 (2020-03-31 revision 67876) [x86_64-linux]
Updated by sawa (Tsuyoshi Sawada) almost 4 years ago
What is the bug?
Updated by FedorKK (Fedor Koshel) almost 4 years ago
The behaviour is super unpredictable. I mean, the problem with floats is known, but it usually happens with precision values, or huge numbers. In this case, if you try to get an integer from 0.29*100 you'll get 28. Which is strange.
If you think, this is just another float discuss, you can close the ticket. But for me the work with simple numbers should be more predictable.
Updated by ko1 (Koichi Sasada) almost 4 years ago
FYI:
$ python
Python 2.7.17 (default, Apr 15 2020, 17:20:14)
[GCC 7.5.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 0.29 * 100
28.999999999999996
>>> 0.29 * 100.0
28.999999999999996
>>> 0.28 * 100
28.000000000000004
>>> 0.28 * 100.0
28.000000000000004
>>> 0.27 * 100.0
27.0
>>> 0.27 * 100
27.0
Updated by FedorKK (Fedor Koshel) almost 4 years ago
Yes, but for example in Go:
func main() {
fmt.Printf("%f", 0.29 * 100)
fmt.Println()
fmt.Printf("%f", 0.28 * 100)
fmt.Println()
fmt.Printf("%f", 0.27 * 100)
}
29.000000
28.000000
27.000000
Updated by sawa (Tsuyoshi Sawada) almost 4 years ago
as well in Ruby:
"%f" % (0.29 * 100) # => "29.000000"
"%f" % (0.28 * 100) # => "28.000000"
"%f" % (0.27 * 100) # => "27.000000"
Updated by FedorKK (Fedor Koshel) almost 4 years ago
Ok, let's close it. It's really doesn't make any sense to improve the standard representation. But still:
func main() {
fmt.Println(0.29 * 100 == 29.0)
}
true
irb(main):001:0> 0.29 * 100 == 29.0
=> false
Updated by hsbt (Hiroshi SHIBATA) almost 4 years ago
- Status changed from Open to Rejected
Updated by duerst (Martin Dürst) almost 4 years ago
Just as an add-on:
Go has similar effects to those reported here for Ruby, see e.g. https://stackoverflow.com/questions/33640943/golang-float-arithmetic.
@FedorKK (Fedor Koshel), if you can find out why e.g. fmt.Println(0.29 * 100 == 29.0)
prints true in Go, please tell us.