简体   繁体   English

Java:处理Exponentiation

[英]Java: Dealing with Exponentiation

I have a problem with this program where I have to calculate the value of base^expo, and the base is a real number whereas the exponent is an integer. 我有这个程序的问题,我必须计算base ^ expo的值,base是实数,而exponent是整数。 With (95.123)^12 I'm expecting 548815620517731830194541.899025343415715973535967221869852721 , but my program produces 548815620517732160000000.000000 , which is wrong. 随着(95.123)^12我期待548815620517731830194541.899025343415715973535967221869852721 ,但我的程序产生548815620517732160000000.000000 ,这是错误的。 Please suggest a better approach. 请建议一个更好的方法。

// declare variables and read values
double myBase = scan.nextDouble(); 
int myExponent = scan.nextInt();

// display result
System.out.printf("%f", Math.pow(myBase, myExponent));

try to use BigDecimal 尝试使用BigDecimal

example: 例:

BigDecimal base = new BigDecimal("some number");
int exponent = ..;

BigDecimal result = base.pow(exponent);

The double type in Java is a IEEE double and has only 53 bits of precision. Java中的double类型是IEEE双精度,只有53位精度。 Because of this, you will get the closest double value possible to the true answer. 因此,您将获得最接近真实答案的double值。

Because of the large magnitude of the result, the closest double values are quite a bit more than 1 apart. 由于结果的大幅度,最接近的double值相差大于1 You can verify this by calling the Math.ulp method (unit in the last place). 您可以通过调用Math.ulp方法 (最后一个单位)来验证这一点。

System.out.println(Math.ulp(Math.pow(myBase, myExponent)));

This outputs: 这输出:

6.7108864E7

Even with the precision, consecutive double values are 67 million apart. 即使精确度,连续的double值也相差6700万。

As an alternative, you can use BigDecimal s instead, eg 作为替代方案,您可以使用BigDecimal ,例如

BigDecimal myBase= new BigDecimal(scan.next());
int myExponent= scan.nextInt();

//displays result
System.out.println(myBase.pow(myExponent));

Output: 输出:

548815620517731830194541.899025343415715973535967221869852721

Note that pow here takes an int , not another BigDecimal . 请注意, 此处的pow采用int ,而不是另一个BigDecimal

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM