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. , ... .
!