Why does Ruby add precision / numbers when calculating a mod?

I need to do some calculations with coordinates and stumble upon this (at least for me) strange behavior. Can someone explain why this is happening?

$ long
=> 49.0126760222489
$ long % long.floor
=> 0.012676022248896857

I expected the last line to be evaluated only by numbers after the period from long, but instead, it is added still 6857, attached to the end.

Why is he adding numbers?

Where did the information come from?

+4
source share
2 answers

, . ., , 0.0126760222489 % 1.0 1.0126760222489 % 1.0. , , no-IEEE754 float/doubles , Ruby .

6543.21.modulo(137)      #=> 104.21
6543.21.modulo(137.24)   #=> 92.9299999999996

, . , Ruby 2.3.1 :

pry(main)> 6543.21.modulo(137)
=> 104.21000000000004

:

[30] pry(main)> 10.0126760222489 - 0.0
=> 10.0126760222489
[31] pry(main)> 10.0126760222489 - 1.0
=> 9.0126760222489
[32] pry(main)> 10.0126760222489 - 2.0
=> 8.0126760222489
[33] pry(main)> 10.0126760222489 - 3.0
=> 7.0126760222489
[34] pry(main)> 10.0126760222489 - 4.0
=> 6.0126760222489
[35] pry(main)> 10.0126760222489 - 5.0
=> 5.0126760222489
[36] pry(main)> 10.0126760222489 - 6.0
=> 4.0126760222489
[37] pry(main)> 10.0126760222489 - 7.0
=> 3.0126760222489004

, , . - , bigdecimal ( Ruby),

require 'bigdecimal'

BigDecimal('6543.21').modulo(137).to_s
=> "0.10421E3"

BigDecimal('6543.21').modulo(137).to_f
=> 104.21

, "bigdecimal" .

+2

, Ruby, :

, , , , theyre , , .

. , ruby-doc.org.

+3

Source: https://habr.com/ru/post/1656813/


All Articles