Java Math.pow()
方法
原文:https://www.studytonight.com/java-examples/java-math-pow-method
pow()
法(幂的缩写)是用来求一个数的幂与另一个数的幂的乘积。它是java.lang package
的 Math
班的一部分。它返回一个双数值。
如果我们想将输出转换成其他类型,就需要显式转换。该方法的一般签名如下所示。
public static double pow(double base, double power)
示例:Java pow()
方法
让我们看几个例子来了解它的工作原理。
import java.lang.Math;
public class PowDemo
{
public static void main(String[] args)
{
double d1 = Math.pow(3, 5);
double d2 = Math.pow(3.5, 1.5);
int i = (int) Math.pow(3.5, 1.5);//Casting is required for int type
System.out.println("3 raised to the power 5: " + d1);
System.out.println("3.5 raised to the power 1.5: " + d2);
System.out.print("3.5 raised to the power 1.5(for int type): " + i);
}
}
3 升至 5 次方:243.0 3.5 升至 1.5 次方:6.547900426854397 3.5 升至 1.5 次方(对于 int 型):6
我们也可以用它来求数字的平方根或立方根。
import java.lang.Math;
public class PowDemo
{
public static void main(String[] args)
{
double squareRoot = Math.pow(16, 0.5);
double cubeRoot = Math.pow(27, (1.0 / 3));
System.out.println("Square root of 16 is: " + squareRoot);
System.out.print("Cube root of 27 is: " + cubeRoot);
}
}
16 的平方根是:4.0 27 的立方根是:3.0
幂()方法的特例
有几个特例值得一提。
- 如果第二个参数(幂)为正或负零,则返回 1.0。
- 如果第二个参数是 1.0,那么它只返回第一个参数。
- 如果第二个参数是 NaN(不是数字),那么它返回 NaN。
- 如果第一个参数是 NaN,第二个参数是非零的,那么它返回 NaN。
- 如果第一个参数是 NaN,但是第二个参数是零,那么它返回 1。
import java.lang.Math;
public class PowDemo
{
public static void main(String[] args)
{
System.out.println("When Second parameter is zero:");
System.out.println(Math.pow(5.0, 0.0));
System.out.println(Math.pow(5.0, -0.0));
System.out.println("When Second parameter is one:");
System.out.println(Math.pow(5.0, 1));
System.out.println("When Second parameter is NaN:");
System.out.println(Math.pow(5.0, Double.NaN));
System.out.println("When first parameter is NaN and second parameter is non-zero:");
System.out.println(Math.pow(Double.NaN, 14));
System.out.println("When first parameter is NaN and second parameter is zero:");
System.out.println(Math.pow(Double.NaN, 0));
}
}
当第二个参数为零时: 1.0 1.0 当第二个参数为 1 时: 5.0 当第二个参数为 NaN 时: NaN 当第一个参数为 NaN 且第二个参数为非零时: NaN 当第一个参数为 NaN 且第二个参数为零时: 1.0
还有一些特殊情况。简单的指数数学用于理解输出。例如,我们知道-1 的平方根不是实数。如果我们尝试用 pow()做这个,我们应该得到 NaN 值。
import java.lang.Math;
public class PowDemo
{
public static void main(String[] args)
{
System.out.print("Square root of -1: " + Math.pow(-1, 0.5));
}
}
1 的平方根:NaN
我们也知道,一个正的值提升到无穷大,就会趋向于正无穷大。正值,当上升到负无穷大时,趋向于零。pow()方法也复制了这一点。
import java.lang.Math;
public class PowDemo
{
public static void main(String[] args)
{
System.out.println("Positive Value raised to Infinity: " + Math.pow(5, Double.POSITIVE_INFINITY));
System.out.print("Positive Value raised to Negative Infinity: " + Math.pow(5, Double.NEGATIVE_INFINITY));
}
}
正值升至无穷大:无穷大 正值升至负无穷大:0.0
摘要
在这个简短的教程中,我们学习了如何使用java.lang.Math
类的pow()
方法将一个数提升到给定的幂。我们还研究了使用这种方法时可能出现的一些特殊情况。