Ruby Floating Point Math - accuracy issue in Sum Calc

Good morning,

I am having problems with floating point math and are completely lost in ".to_f", "* 100" and ".0" !!

I was hoping that someone could help me with my specific problem, and also explain why their solution works, so that I understand this next time.

My program should do two things:

  • Make a list of decimals, determine if they summarize exactly 1.0
  • Determine the difference between 1.0 and the sum of numbers - set the value of the variable to the exact difference to make the sum equal to 1.0.

For instance:

  • [0.28, 0.55, 0.17] → should sum up to 1.0, however I keep getting 1.xxxxxx. I implement the amount as follows:

    sum = array.inject(0.0){|sum,x| sum+ (x*100)} / 100
    
  • The reason I need this functionality is because I read the set of decimal places that come from excel. They are not 100% accurate (they lack decimal points), so the amount is usually obtained from 0.999999xxxxx or 1.000xxxxx. For example, I get values ​​similar to the following:

    0.568887955,0.070564759,0.360547286
    

To fix this, I normally take the sum of the first numbers n-1, and then slightly change the final number so that all numbers together add up to 1.0 (must correspond to validation using the above equation or any other in the end). I am currently implementing this as follows:

          sum = 0.0
          array.each do |item|
            sum += item * 100.0
          end
          array[i] = (100 - sum.round)/100.0

, , , , . , ( ), . , , . , - .. 0,56 0,5623225. , ... .

!

+5
3

, , . Ruby , . , , BigDecimal, Rational Complex, , .

, BigDecimal, , ( , ).

Excel , "0.9987" , , .

require "bigdecimal"
BigDecimal("0.9987")

. 0.9987. 0.998732109, - , 0.9987. . , .

, Excel (.. #to_f 'd them), BigDecimal, 1.

1 - array.map{|v| BigDecimal(v)}.reduce(:+)
+8

:

  • float round(2) : 12.341.round(2) # => 12.34

  • (.. )

  • BigDecimal, , BigDecimal .

+2

, , IEEE .

People usually did small calculations, while still dealing with problems of accuracy and precision. They will do this by controlling the algorithms they will use and understanding how to represent functions more deeply. I think you can make a mistake by discarding this better understanding and assuming another solution is a solution.

For example, no polynomial representation of a function will deal with an asymptote or singularity properly.

Do not cast floating point so fast. I could be that smarter about how you use them would be great.

0
source

All Articles