JAVA: Imprecise output for double-based calculation

In the following program fragment, the answer is supposed to be -490.5; however, it displays as -490.50000000000006
Is this behavior expected, and is there a way to avoid?

Thanks,
Steve



		double Acceleration = -9.81;
		double Time = 10;
		double InitialVelocity = 0;
		double InitialPosition = 0;
		
		double Position;
		
		Position = 0.5 * (Acceleration * Time * Time) + (InitialVelocity*Time) + InitialPosition;
		
		System.out.println("The object fell " + Position + " meters in " + Time + " seconds.");

Open in new window


NOTE: If I replace
Time * Time

Open in new window


with
Math.pow(Time,2)

Open in new window

I do not have this problem.
LVL 4
Stephen KairysTechnical Writer - ConsultantAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

JohnBusiness Consultant (Owner)Commented:
Your number of significant figures above is beyond 16 and that is just the way binary computers (all computers) work. Round to the number of figures you need and you should be fine. Excel works the same way.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Stephen KairysTechnical Writer - ConsultantAuthor Commented:
OK, is there a Round() method? (Maybe in the Math class?)
Thanks.
JohnBusiness Consultant (Owner)Commented:
There is a round function in Excel, of course. Java won't be the same. Here is an example

http://mathbits.com/MathBits/Java/DataBasics/money.htm

I hope that helps.
Angular Fundamentals

Learn the fundamentals of Angular 2, a JavaScript framework for developing dynamic single page applications.

Stephen KairysTechnical Writer - ConsultantAuthor Commented:
OK thanks.  I'll check this out over the weekend or on Monday - brain too tired to dive into it now.:)  Thanks for the help!

Steve
JohnBusiness Consultant (Owner)Commented:
No problem. There are a lot of example of Java rounding - many of them from Stack Overflow which we cannot link to in here.
CEHJCommented:
Just format your output to the appropriate number of decimal places (here one):

System.out.printf("The object fell %1.f meter(s) in %1.f second(s).%n", Position, Time);

Open in new window


btw, variable names in Java begin lower case and are in camel case
Stephen KairysTechnical Writer - ConsultantAuthor Commented:
CEHJ.
OK, that will work.  Two follow-ups if you don't mind:

1. I'm wondering, how accepted is it to use legacy C functions such as printf()?

 2.>>btw, variable names in Java begin lower case and are in camel case<<
Is the above merely a convention? Or will the compiler nail me if I don't follow this rule?

Thanks!
Steve
CEHJCommented:
I'm wondering, how accepted is it to use legacy C functions such as printf()?

Totally. It's not 'legacy' ;) It's relatively recent and a powerful borrowing from C

Is the above merely a convention?

Yes. I prefer to think of it as best practice
Stephen KairysTechnical Writer - ConsultantAuthor Commented:
@CEJH
OK, I tried thee %f.1 (actually %f.2 since I want two decimal places :) ). However...the following runtime errors appeared:

Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = '2'
	at java.util.Formatter.checkText(Unknown Source)
	at java.util.Formatter.parse(Unknown Source)
	at java.util.Formatter.format(Unknown Source)
	at java.io.PrintStream.format(Unknown Source)
	at java.io.PrintStream.printf(Unknown Source)
	at MIT_Assignment_1_1.main(MIT_Assignment_1_1.java:27)

Open in new window


Perhaps you meant %.2f? I tried that one and it worked. if you agree, would you be able to repost your answer with this correction so I can credit you with points? :)

Thanks
Steve
JohnBusiness Consultant (Owner)Commented:
Remember also that your question asked if the long decimal was expected behaviour. CEHJ is giving good guidance on rounding.
CEHJCommented:
Yes, sorry - that should have been

System.out.printf("The object fell %.1f meter(s) in %.1f second(s).%n", Position, Time);

Open in new window

and 2 DP
System.out.printf("The object fell %.2f meter(s) in %.2f second(s).%n", Position, Time);

Open in new window

Stephen KairysTechnical Writer - ConsultantAuthor Commented:
@John Hurst - Very nice per DecimalFormat().

So, I have:
DecimalFormat decFormatPosition = new DecimalFormat("0.00");

Open in new window


which, if I'm thinking correctly, declares the object, instantiates it, and calls the constructor, which uses the "0.00" parameter.

Now, in the example code I've seen, I don't see any call to a destructor. Maybe I'm thinking too much in the mode of C++ or C, but why don't you need to deallocate the memory allocated (granted, behind the scenes) via the code snippet above.

Thanks,
Steve
CEHJCommented:
DecimalFormat is relatively clunky to String.format and System.out.printf

but why don't you need to deallocate the memory allocated
Because memory in Java is allocated automatically and reclaimed automatically via garbage collection
Stephen KairysTechnical Writer - ConsultantAuthor Commented:
CEJH: Nice!  As a C programmer, I appreciate not having to worry about that concept, then! :)
Thanks.
Stephen KairysTechnical Writer - ConsultantAuthor Commented:
Thank you both. So, I've learned two ways to format this output.

Been a pleasure as always! :)

Cheers,
Steve
JohnBusiness Consultant (Owner)Commented:
Stephen - I am glad CEHJ got it sorted out for you (impressive work) and I was happy to help at the beginning.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.