As an extension to my answer to this question, I am trying to split a real number in such a way that each of the two numbers differ by atmost 1 in their last digit (subject to the limitations of floating point arithmetic representation).
For example:
7 => 4, 3
7.2 => 3.6, 3.6
7.3 => 3.7, 3.6 (or 3.5999999999999996) -- I understand this is a corner case and it is alright
7.25 => 3.63, 3.62
7.225 => 3.613, 3.612
To clarify, the resultant addends must contain the same number of digits as the original number.
This is what I've come up with so far.
var x = 7.3;
if(x != Math.round(x)) {
var p1 = Math.ceil((x / 2) * 10) / 10;
} else {
var p1 = Math.ceil(x / 2);
}
var p2 = x - p1;
console.log(p1, p2);
This works for whole numbers and numbers with one decimal after the point as of now. I believe the general solution would involve figuring out how many digits appear after the point.
I am unsure of how to do this, but I believe one solution would involve converting to a string, splitting on '.'
, finding the digit count, and then multiplying/dividing by the appropriate power of 10... basically extending the code I've written, so it works for any arbitrary number.
Javascript solutions preferred, but a python solution would also work. Any help would be appreciated. Thank you!