Rounding error with pi
문제
I am trying to make a sequence of code that calculates the volume of a cone based on a user input height and radius (see below).
My problem is that the answer comes out wrong (but not by a long way). Using the example of height = 5, radius = 10, I get an answer from the code of 500 (treating pi as exactly 3), but calculating manually I get ~523.
I'm assuming it has something to do with the variable type I am declaring pi under (double then converting to long) but I have struggled to make any other combination of variable types work.
What is the correct version of this below that will store pi properly (to at least 5 or 6 dec places)?
double piDouble = Math.PI;
long height = Long.parseLong(heightString);
long pi = (new Double(piDouble)).longValue();
long radius = Long.parseLong(radiusString);
long volumeBase = (pi*(radius*radius)*height) / 3;
해결책
long pi = (new Double(piDouble)).longValue();
is a long, so it is equal to 3
, exactly.
If you need more precision, use double all the way, and round at the end only. This should give you the result you expect:
double piDouble = Math.PI;
long height = Long.parseLong(heightString);
long radius = Long.parseLong(radiusString);
double volumeBase = (piDouble * (radius * radius) * height) / 3;
You can then round the result if you need to:
long roundedDownVolume = (long) volumeBase; //round down
long roundedVolume = Math.round(volumeBase); //or round to the closest long
다른 팁
You should use BigDecimal for this kind of arithmetic.