在日志函数中使用递归幂函数,无需Math.functions

时间:2016-11-10 12:19:09

标签: java math recursion

喜欢它在标题中说我有问题,我需要自己动力和记录方法,并在我的输入上使用它们。 我的功能函数似乎没问题,直到我尝试在我的loga(b)函数中使用它。 一个问题是我不理解我的日志方法中的for循环,因为我在类中复制了一个以便稍后理解它。另一个问题是我不知道内置的Math.pow()是如何工作的,如果我有代码或伪代码,我可以猜测我自己的幂函数是如何不同的。 提前谢谢,请放轻松我,我仍然很新。

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

1 个答案:

答案 0 :(得分:-1)

您的幂方法仅适用于整数i2,否则递归永远不会终止。

对于非整数i2,在缩小到01之间后,您至少可以进行一些线性插值。对于大基值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”。