问题
I would like to calculate (1.0-p)^n
where p is a double between 0 and 1 (often very close to 0) and n is a positive integer that might be on the order of hundreds or thousands (perhaps larger; I'm not sure yet). If possible I would love to just use Java's built in java.lang.Math.pow(1.0-p, n)
for this, but I'm slightly concerned that there might be a gigantic loss of accuracy/precision in doing so with the range of values that I'm interested in. Does anybody have a rough idea of what kind of error I might expect using Java's implementation? I'm not sure what goes on under the hood in their implementation (logs and/or Taylor approximations?), so I can't hazard a good guess.
I'm mostly concerned about relative error (i.e. not being off by more than an order of magnitude). If the answer turns out to be that Java's implementation will produce too much error, do you have any good library recommendations (but again, I'm hoping this shouldn't be needed)? Thanks.
回答1:
According to the API doc:
The computed result must be within 1 ulp of the exact result.
So I don't think you need to worry about the implementation so much as about the limits of floating-point accuracy. You may want to consider using BigDecimal.pow()
if accuracy rather than performance is your primary concern.
回答2:
You can take a look at the java.land.Math class source file and see if you can understand the exact method. Here is the link, http://www.docjar.com/html/api/java/lang/Math.java.html.
回答3:
Some empirical results:
public static void main(String[] args)
{
double e = 0.000000000001d;
System.out.println(Math.pow(1-e, 1.0d/e));
float f = 0.000001f;
System.out.println(Math.pow(1-f, 1.0f/f));
}
0.36788757938730976
0.3630264891374932
Both should converge to 1/e (0.36787944....) so obviously float is out of the question but double might have enough precision for you.
来源:https://stackoverflow.com/questions/5558646/how-accurate-precise-is-java-lang-math-powx-n-for-large-n