I’m learning TDD and, decided to create a Calculator class to start.
i did the basic first, and now I’m on the Square Root function.
I’m using this method to get the root http://www.math.com/school/subject1/lessons/S1U1L9DP.html
i tested it with few numbers, and I always get the accurate answers.
is pretty easy to understand.
Now I’m having a weird problem, because with some numbers, im getting the right answer, and with some, I don’t.
I debugged the code, and found out that I’m not getting the right answer when I use subtract.
I’m using decimals to get the most accurate result.
when I do:
18 / 4.25
I am currently getting: 4.2352941176470588235294117647
when it should be: 4.2352941176470588235294117647059 (using windows calculator)
in the end of the road, this is the closest i get to the root of 18:
4.2426406871192851464050688705 ^ 2 = 18.000000000000000000000022892
my question is:
Can i get more accurate then this?
4.2352941176470588235294117647contains 29 digits.decimalis define to have 28-29 significant digits. You can’t store a more accurate number in adecimal.What field of engineering or science are you working in where the 30th and more digits are significant to the accuracy of the overall calculation?
(It would also, possibly, help if you’d shown some more actual code. The only code you’ve shown is
18 / 4.25, which can’t be an actual expression in your code, since the second number is adoubleliteral, and you can’t assign the result of this expression to adecimalwithout a cast).If you need arbitrary precision, then there isn’t a standard “BigRational” type, but there is a
BigInteger. You could use that to construct aBigRationaltype if you need that (storing numerator and denominator as two separate integers). One guess of why there isn’t a standard type yet is that decisions on when to e.g. normalize such rationals may affect performance or equality comparisons.