Created
June 4, 2015 21:28
-
-
Save rjurado01/f6a637d4ad77a0c30817 to your computer and use it in GitHub Desktop.
Solve float point error
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sum(a, b) | |
a_dec = a.to_s.split('.')[1] | |
b_dec = b.to_s.split('.')[1] | |
len1 = a_dec ? a_dec.size : 0 | |
len2 = b_dec ? b_dec.size : 0 | |
max_len = len1 > len2 ? len1 : len2 | |
factor = 10 ** max_len | |
if max_len > 0 | |
(a * factor + b * factor) / factor.to_f | |
else | |
a + b | |
end | |
end | |
p 0.1 + 0.2 | |
p 1.1 - 1 | |
p 1 + 2 | |
p "---------------" | |
p sum(0.1, 0.2) | |
p sum(1.1, -1) | |
p sum(1, 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment