import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double i1;
double i2;
System.out.print("type your a:");
i1 = input.nextDouble();
System.out.print("type your b:");
i2 = input.nextDouble();
input.close();
sumRange(i1, i2);
power(i1, i2);
log(i1, i2);
System.out.println("Sum from a to b: " + sumRange(i1, i2) + "\nFibonacci for A: " + fibonacci(i1)
+ "\nFibonacci for B: " + fibonacci(i2) + "\nA^B:" + power(i1, i2) + "\na%b: " + mod(i1, i2)
+ "\nloga (b)" + log(i1, i2));
}
// if I'm honest I don't understand how the log code works exactly,
// what I do know is that this code calculates the correct log
// with Math.pow() function
// My own power function doesn't seem to work and I don't know how the
// MAth.pow()
// function is different from mine
static double log(double i1, double i2) {
double value = 0;
for (double i = 1; i > .001; i /= 10) {
while (!(power(i1, value) > i2)) {
value += i;
}
value -= i;
}
return value;
}
static double power(double i1, double i2) {
if (i2 == 0) {
return 1;
}
if (i2 == 1) {
return i1;
}
// The line below seems to cause problems since used in log(double,
// double) method
return i1 * power(i1, i2 - 1);
}
// I excluded my 3 other methods as they work fine and don't depend on
// each other to work
答案 0 :(得分:-1)
您的幂方法仅适用于整数i2
,否则递归永远不会终止。
对于非整数i2
,在缩小到0
和1
之间后,您至少可以进行一些线性插值。对于大基值i1
而言,这是一个不好的近似值,但总比没有好。
if( 0<=i2 and i2 <=1) return 1+i2*(i1-1);
负面i2
呢?
if( i2 < 0 ) return 1/power(i1,-i2);
谷歌的“libm / exp.c”用于C
标准库中指数的专业实现,有不同的变体,类似于“libm / pow.c”。