Reputation: 35
I am relatively new to java so go easy on me,
I have the function g(x) = 8x^3
i have to output the inverse of g after g. So:
inverseGAG = ((Math.pow(functionG, 1.0/3))/8);
It is giving me ALMOST the correct answer for example, lets say x = 4
g(4) = 512
, so the inverseG of 512 would be the cubic root of 512 which is 8, then we divide by 8 = 1.
my program is outputting 0.9999999999
and i have no idea why?
Upvotes: 2
Views: 564
Reputation: 66886
Other comments are correct that you can't expect exact results in floating-point arithmetic, and that usually BigDecimal
is the answer. However there is no means to compute any non-integer power of a number in BigDecimal
since the result may be irrational, at the least. So that's not quite an answer.
I wanted to highlight Louis Wasserman's comment, which may be the most practical answer here. Math.cbrt()
will give significantly better precision here, and in fact you will get 1.0
for your argument. I imagine it uses a specialization of Newton's method for the case of a cube root, which will give better accuracy than the general pow()
method, which I expect uses logarithms.
See also of course Math.sqrt()
.
Upvotes: 0
Reputation: 33029
You're expecting an exact answer from inexact number representation. Assuming you're using the double
type, then there are only 64 bits available to store values in your calculation. On top of that, the values are stored in binary (base 2), not decimal (base 10), and the fractions that can be represented exactly in these two bases are different. For example, 0.110 = 0.00̅0̅1̅1̅2.
Because of the limited precision available, rounding errors are bound to come up when you're doing floating-point arithmetic. If you'd like to learn some more of the details involved with floating-point math, you can look at Introduction to Programming in Java, 9.1 Floating point, or What Every Computer Scientist Should Know About Floating-Point Arithmetic.
In your case, switching to using Math.cbrt
will probably yield a good enough answer. More generally, doing something like rounding to 10 decimal places would probably give you a good enough answer as well—but there's nothing you can do to get the right answer in all cases.
Upvotes: 1