Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Math conundrum



On Dec 20, 2004, at 4:44 AM, Mike Hall wrote:

if it's already a double, then it's already base-2 "imprecise", and
susceptible as such.  Converting it to a String buys you nothing,
though you might do new BigDecimal("1.8");

This was my guess and one other person confirmed off-list. Assuming I have
been forced to a interim calculation double which has resulted in a
"imprecise" base-2 value. Then doing something like String isprecise =
Double.toString(interim); BigDecimal backtoprecise = new
BigDecimal(isprecise); will not work. Because isprecise won't be.

If N is the number which can't be store precisely as a double but can be stored precisely as a decimal, then doing this
double d = N;
BigDecimal b = new BigDecimal(Double.toString(d));
... will only work if Double.toString(d) gets lucky and happens to print the imprecise number back it its precise decimal form. Don't count on it.



An easy but inefficient way to get a numerical (non-string) value of
the form a.b into BigDecimal precisely is to say:    new
BigDecimal(ab).movePointLeft(1)
For example, new BigDecimal(18).movePointLeft(1) is 1.8 exactly.

Is what you are saying that you can sidestep the issue by trying to work
integer or fixed-point somehow and only when done convert back to the
floating-point representation?

A finite-length decimal number is just an integer with a decimal point somewhere. So if your number N *can* be stored precisely as a decimal, then the above will do it in BigDecimal. If N is irrational or has a finite-length longer than 2^32, then you're out of luck in any case, of course.


But you have to consider what you need that precision for: BigDecimal is primarily for explicit math functions that are highly specialized in need. If double's precision is not enough for you, you should very seriously reconsider the approach to your application before going to something as slow as BigDecimal.

Sean

_______________________________________________
Do not post admin requests to the list. They will be ignored.
Java-dev mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/java-dev/email@hidden

This email sent to email@hidden
References: 
 >Re: Math conundrum (From: Sean Luke <email@hidden>)
 >Re: Math conundrum (From: "Mike Hall" <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.