我正在尝试为 Math.pow 编写手动代码,并且也使用 BigDecimal 数据类型,因为稍后我将使用非常小的值。
我得到了 math.pow 的代码,然后我尝试将其转换为 BigDecimal。
public static double power(double base, int exponent) {
double ans = 1;
if (exponent != 0) {
int absExponent = exponent > 0 ? exponent : (-1) * exponent;
for (int i = 1; i <= absExponent; i++) {
ans *= base;
}
if (exponent < 0) {
// For negative exponent, must invert
ans = 1.0 / ans;
}
} else {
// exponent is 0
ans = 1;
}
return ans;
}
}
我将 double 和 int 数据类型转换为 BigDecimal 并尝试相应地更改代码,但不知何故我没有得到正确的结果。
public static BigDecimal powerBig(BigDecimal base, BigDecimal exponent) {
BigDecimal ans= new BigDecimal(1.0);
BigDecimal k= new BigDecimal(1.0);
BigDecimal t= new BigDecimal(-1.0);
BigDecimal no= new BigDecimal(0.0);
if (exponent != no) {
BigDecimal absExponent = exponent.signum() > 0 ? exponent : t.multiply(exponent);
for (int i = 1 ; i <= absExponent.signum(); i++) {
ans =ans.multiply(base);
}
if (exponent.signum() < 0) {
// For negative exponent, must invert
ans = k.divide(ans);
}
} else {
// exponent is 0
ans = k;
}
return ans;
}
我正在尝试运行它
BigDecimal check = new BigDecimal (4.0);
BigDecimal Euler = new BigDecimal (2.7182818);
powerBig(Euler,check);
但是我得到的输出只是欧拉值。有人可以帮我解决代码中的错误吗?
将指数类型更改为 int 后,代码现在运行
public static BigDecimal powerBig(BigDecimal base, int exponent) {
BigDecimal ans= new BigDecimal(1.0);
BigDecimal k= new BigDecimal(1.0);
//BigDecimal t= new BigDecimal(-1.0);
//BigDecimal no= new BigDecimal(0.0);
if (exponent != 0) {
int absExponent = exponent > 0 ? exponent : (-1)*exponent;
for (int i = 1 ; i <= absExponent; i++) {
ans =ans.multiply(base);
}
if (exponent < 0) {
// For negative exponent, must invert
ans = k.divide(ans);
}
} else {
// exponent is 0
ans = k;
}
return ans;
}
最佳答案
你的问题是,如果数字是正数、零或负数,BigDecimal.sigNum() 返回 1、0 或 -1,因此 absExponent.sigNum() 将始终返回 1,循环将在第一次执行时结束
此版本适用于 euler 示例
public static BigDecimal powerBig(BigDecimal base, BigDecimal exponent) {
BigDecimal ans= new BigDecimal(1.0);
BigDecimal k= new BigDecimal(1.0);
BigDecimal t= new BigDecimal(-1.0);
BigDecimal no= new BigDecimal(0.0);
if (exponent != no) {
BigDecimal absExponent = exponent.signum() > 0 ? exponent : t.multiply(exponent);
while (absExponent.signum() > 0){
ans =ans.multiply(base);
absExponent = absExponent.subtract(BigDecimal.ONE);
}
if (exponent.signum() < 0) {
// For negative exponent, must invert
ans = k.divide(ans);
}
} else {
// exponent is 0
ans = k;
}
return ans;
}
BigDecimal 类也有一个 pow 函数,所以如果你想保持简单,你可以直接输入
BigDecimal Euler = new BigDecimal (2.7182818);
Euler.pow(4);
关于java - 在 Java 中使用 BigDecimal 的手动 Math.pow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42649163/