我正在尝试使用BigDecimal数据类型为Math.pow编写一个手动代码,因为我稍后将处理非常小的值。
我得到了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);但我得到的输出只有Euler值。有人能帮我纠正代码中的错误吗?
将指数类型更改为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;
}发布于 2017-03-07 21:30:36
您的问题是,如果数字为正、零或负,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);https://stackoverflow.com/questions/42649163
复制相似问题