Project

General

Profile

Bug #15312

Ruby gives me wrong result for plus operation

Added by kot-begemot (Max Zet) 10 months ago. Updated 10 months ago.

Status:
Rejected
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:89839]

Description

Run into this weird issue today. Tried that on rubies 2.5.1p57 and ruby 2.5.3p105 (i believe this is latest stable at the moment).

Here is how to reproduce it

$ irb
2.5.3 :001 >  2.6 + 0.1
 => 2.7 
2.5.3 :002 >  2.7 + 0.1
 => 2.8000000000000003 
2.5.3 :003 >  2.8 + 0.1
 => 2.9

Here some more cases

$ irb
2.5.3 :001 > 2.7 + 0.01
 => 2.71 
2.5.3 :002 > 2.79 + 0.01
 => 2.8 
2.5.3 :003 >  2.8 - 0.1
 => 2.6999999999999997 
2.5.3 :004 > 2.79 + 0.01
 => 2.8 
2.5.3 :005 > 2.81 - 0.01
 => 2.8000000000000003 

Haven't discovered other cases yet, if will catch them, will post them here

History

Updated by oleynikov (Alexander Oleynikov) 10 months ago

This is not a bug, that's how floating point arithmetic works in accordance with the IEEE 754 standard.

You can read more about that on Wikipedia or in this article: https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

To get mathematically correct results you should be using BigDecimal or Rational.

require 'bigdecimal'
BigDecimal('2.7') + BigDecimal('0.1') #=> 0.28e1

Updated by marcandre (Marc-Andre Lafortune) 10 months ago

  • Status changed from Open to Rejected

Updated by nobu (Nobuyoshi Nakada) 10 months ago

You can write rational numbers by r suffix.

p 0.1r + 0.2r #=> (3/10)

As I found these literals (r and i) have not been mentioned in doc/syntax/, added them now (r65773).

#4

Updated by nobu (Nobuyoshi Nakada) 10 months ago

  • Description updated (diff)

Also available in: Atom PDF