Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 大十进制的对数_Java_Bigdecimal_Logarithm - Fatal编程技术网

Java 大十进制的对数

Java 大十进制的对数,java,bigdecimal,logarithm,Java,Bigdecimal,Logarithm,如何计算大十进制的对数?有人知道我可以使用什么算法吗 到目前为止,我在谷歌上找到了一个(无用的)想法,就是转换成double并使用Math.log 我将提供所需答案的精确性 编辑:任何基础都可以。如果以x为基数更简单,我会这样做。一个适用于大数的黑客小算法使用关系log(AB)=log(A)+log(B)。以下是以10为底的操作方法(您可以轻松地将其转换为任何其他对数底): 计算答案中的小数位数。这是对数的整数部分,加上一。例如:floor(log10(123456))+1是6,因为123456

如何计算大十进制的对数?有人知道我可以使用什么算法吗

到目前为止,我在谷歌上找到了一个(无用的)想法,就是转换成double并使用Math.log

我将提供所需答案的精确性


编辑:任何基础都可以。如果以x为基数更简单,我会这样做。

一个适用于大数的黑客小算法使用关系
log(AB)=log(A)+log(B)
。以下是以10为底的操作方法(您可以轻松地将其转换为任何其他对数底):

  • 计算答案中的小数位数。这是对数的整数部分,加上一。例如:
    floor(log10(123456))+1
    是6,因为123456有6位数字

  • 如果您只需要对数的整数部分,您可以在这里停止:只需从步骤1的结果中减去1

  • 要获得对数的小数部分,请将数字除以
    10^(位数)
    ,然后使用
    math.log10()
    (或其他任何方法;如果没有其他可用方法,则使用简单的级数近似法)计算对数,并将其添加到整数部分。示例:要获得
    log10(123456)
    的小数部分,请计算
    math.log10(0.123456)=-0.908…
    ,并将其添加到步骤1的结果中:
    6+-0.908=5.092
    ,即
    log10(123456)
    。请注意,您基本上只是在大数字的前面加上一个小数点;在您的用例中,可能有一个很好的方法来优化它,对于非常大的数字,您甚至不需要抓取所有的数字--
    log10(0.123)
    非常接近
    log10(0.123456789)


  • 你可以使用

    log(a * 10^b) = log(a) + b * log(10)
    
    基本上,
    b+1
    将是数字中的位数,
    a
    将是一个介于0和1之间的值,您可以使用常规的
    double
    算法计算其对数

    或者你可以使用一些数学技巧——例如,接近1的数字的对数可以通过级数展开来计算

    ln(x + 1) = x - x^2/2 + x^3/3 - x^4/4 + ...
    
    取决于你想取什么样的数字作为对数,你可以使用这样的方法


    编辑:要得到以10为底的对数,可以将自然对数除以
    ln(10)
    ,或类似地除以任何其他底。

    这就是我得出的结论:

    //http://everything2.com/index.pl?node_id=946812        
    public BigDecimal log10(BigDecimal b, int dp)
    {
        final int NUM_OF_DIGITS = dp+2; // need to add one to get the right number of dp
                                        //  and then add one again to get the next number
                                        //  so I can round it correctly.
    
        MathContext mc = new MathContext(NUM_OF_DIGITS, RoundingMode.HALF_EVEN);
    
        //special conditions:
        // log(-x) -> exception
        // log(1) == 0 exactly;
        // log of a number lessthan one = -log(1/x)
        if(b.signum() <= 0)
            throw new ArithmeticException("log of a negative number! (or zero)");
        else if(b.compareTo(BigDecimal.ONE) == 0)
            return BigDecimal.ZERO;
        else if(b.compareTo(BigDecimal.ONE) < 0)
            return (log10((BigDecimal.ONE).divide(b,mc),dp)).negate();
    
        StringBuffer sb = new StringBuffer();
        //number of digits on the left of the decimal point
        int leftDigits = b.precision() - b.scale();
    
        //so, the first digits of the log10 are:
        sb.append(leftDigits - 1).append(".");
    
        //this is the algorithm outlined in the webpage
        int n = 0;
        while(n < NUM_OF_DIGITS)
        {
            b = (b.movePointLeft(leftDigits - 1)).pow(10, mc);
            leftDigits = b.precision() - b.scale();
            sb.append(leftDigits - 1);
            n++;
        }
    
        BigDecimal ans = new BigDecimal(sb.toString());
    
        //Round the number to the correct number of decimal places.
        ans = ans.round(new MathContext(ans.precision() - ans.scale() + dp, RoundingMode.HALF_EVEN));
        return ans;
    }
    
    //http://everything2.com/index.pl?node_id=946812        
    公共BigDecimal日志10(BigDecimal b,int-dp)
    {
    final int NUM_OF_DIGITS=dp+2;//需要添加一个以获得正确的dp数
    //然后再加一次,得到下一个数字
    //这样我就可以正确地把它四舍五入了。
    MathContext mc=新的MathContext(整数位数,舍入模式。半偶数);
    //特殊条件:
    //日志(-x)->异常
    //log(1)==0;
    //一个数字的对数小于一=-log(1/x)
    if(b.signum()提供了一个使用本书中的源代码的解决方案。以下内容摘自第12.5章大十进制函数(p330和p331):

    /**
    *计算给定刻度x的自然对数,x>0。
    */
    公共静态BigDecimal ln(BigDecimal x,整数刻度)
    {
    //检查x>0。
    如果(x.signum()0。
    *使用牛顿算法。
    */
    专用静态BigDecimal lnNewton(BigDecimal x,整数刻度)
    {
    int sp1=标度+1;
    双十进制n=x;
    大十进制项;
    //收敛公差=5*(10^-(比例+1))
    BigDecimal公差=BigDecimal.valueOf(5)
    .movePointLeft(sp1);
    //循环直到近似值收敛
    //(两个连续近似值在公差范围内)。
    做{
    //e^x
    BigDecimal eToX=exp(x,sp1);
    //(e^x-n)/e^x
    项=eToX.减去(n)
    .除法(eToX、sp1、BigDecimal.向下四舍五入);
    //x-(e^x-n)/e^x
    x=x.减去(项);
    螺纹屈服强度();
    }而(术语比较(公差)>0);
    返回x.setScale(刻度、大十进制、四舍五入半偶数);
    }
    /**
    *计算给定比例下x的整数根,x>=0。
    *使用牛顿算法。
    *@param x x的值
    *@param索引整数根值
    *@param scale结果的所需比例
    *@返回结果值
    */
    公共静态BigDecimal intRoot(BigDecimal x,长索引,
    整数比例)
    {
    //检查x>=0。
    if(x.signum()<0){
    抛出新的IllegalArgumentException(“x<0”);
    }
    int sp1=标度+1;
    双十进制n=x;
    BigDecimal i=BigDecimal.valueOf(索引);
    BigDecimal im1=BigDecimal.valueOf(索引-1);
    BigDecimal公差=BigDecimal.valueOf(5)
    .movePointLeft(sp1);
    大十进制xPrev;
    //初始近似值为x/index。
    x=x.除法(i,刻度,大十进制,四舍五入半偶数);
    //循环直到近似值收敛
    //(四舍五入后,两个连续近似值相等)。
    做{
    //十^(索引-1)
    BigDecimal xToIm1=intPower(x,索引-1,sp1);
    //x^索引
    大十进制xToI=
    x、 乘法(xToIm1)
    .setScale(sp1,大十进制。四舍五入半偶数);
    //n+(指数-1)*(x^指数)
    大十进制分子=
    n、 加法(im1.乘法(xToI))
    .setScale(sp1,大十进制。四舍五入半偶数);
    //(索引*(x^(索引-1))
    大十进制分母=
    i、 乘法(xToIm1)
    .setScale(sp1,大十进制。四舍五入半偶数);
    //x=(n+(索引-1)*(x^index))/(索引*(x^(索引-1)))
    xPrev=x;
    x=分子
    .除法(分母,sp1,大十进制。向下舍入);
    螺纹屈服强度();
    }而(x.subtract(xPrev).abs().compareTo(公差)>0);
    返回
    
    /**
     * Compute the natural logarithm of x to a given scale, x > 0.
     */
    public static BigDecimal ln(BigDecimal x, int scale)
    {
        // Check that x > 0.
        if (x.signum() <= 0) {
            throw new IllegalArgumentException("x <= 0");
        }
    
        // The number of digits to the left of the decimal point.
        int magnitude = x.toString().length() - x.scale() - 1;
    
        if (magnitude < 3) {
            return lnNewton(x, scale);
        }
    
        // Compute magnitude*ln(x^(1/magnitude)).
        else {
    
            // x^(1/magnitude)
            BigDecimal root = intRoot(x, magnitude, scale);
    
            // ln(x^(1/magnitude))
            BigDecimal lnRoot = lnNewton(root, scale);
    
            // magnitude*ln(x^(1/magnitude))
            return BigDecimal.valueOf(magnitude).multiply(lnRoot)
                        .setScale(scale, BigDecimal.ROUND_HALF_EVEN);
        }
    }
    
    /**
     * Compute the natural logarithm of x to a given scale, x > 0.
     * Use Newton's algorithm.
     */
    private static BigDecimal lnNewton(BigDecimal x, int scale)
    {
        int        sp1 = scale + 1;
        BigDecimal n   = x;
        BigDecimal term;
    
        // Convergence tolerance = 5*(10^-(scale+1))
        BigDecimal tolerance = BigDecimal.valueOf(5)
                                            .movePointLeft(sp1);
    
        // Loop until the approximations converge
        // (two successive approximations are within the tolerance).
        do {
    
            // e^x
            BigDecimal eToX = exp(x, sp1);
    
            // (e^x - n)/e^x
            term = eToX.subtract(n)
                        .divide(eToX, sp1, BigDecimal.ROUND_DOWN);
    
            // x - (e^x - n)/e^x
            x = x.subtract(term);
    
            Thread.yield();
        } while (term.compareTo(tolerance) > 0);
    
        return x.setScale(scale, BigDecimal.ROUND_HALF_EVEN);
    }
    
    /**
     * Compute the integral root of x to a given scale, x >= 0.
     * Use Newton's algorithm.
     * @param x the value of x
     * @param index the integral root value
     * @param scale the desired scale of the result
     * @return the result value
     */
    public static BigDecimal intRoot(BigDecimal x, long index,
                                     int scale)
    {
        // Check that x >= 0.
        if (x.signum() < 0) {
            throw new IllegalArgumentException("x < 0");
        }
    
        int        sp1 = scale + 1;
        BigDecimal n   = x;
        BigDecimal i   = BigDecimal.valueOf(index);
        BigDecimal im1 = BigDecimal.valueOf(index-1);
        BigDecimal tolerance = BigDecimal.valueOf(5)
                                            .movePointLeft(sp1);
        BigDecimal xPrev;
    
        // The initial approximation is x/index.
        x = x.divide(i, scale, BigDecimal.ROUND_HALF_EVEN);
    
        // Loop until the approximations converge
        // (two successive approximations are equal after rounding).
        do {
            // x^(index-1)
            BigDecimal xToIm1 = intPower(x, index-1, sp1);
    
            // x^index
            BigDecimal xToI =
                    x.multiply(xToIm1)
                        .setScale(sp1, BigDecimal.ROUND_HALF_EVEN);
    
            // n + (index-1)*(x^index)
            BigDecimal numerator =
                    n.add(im1.multiply(xToI))
                        .setScale(sp1, BigDecimal.ROUND_HALF_EVEN);
    
            // (index*(x^(index-1))
            BigDecimal denominator =
                    i.multiply(xToIm1)
                        .setScale(sp1, BigDecimal.ROUND_HALF_EVEN);
    
            // x = (n + (index-1)*(x^index)) / (index*(x^(index-1)))
            xPrev = x;
            x = numerator
                    .divide(denominator, sp1, BigDecimal.ROUND_DOWN);
    
            Thread.yield();
        } while (x.subtract(xPrev).abs().compareTo(tolerance) > 0);
    
        return x;
    }
    
    /**
     * Compute e^x to a given scale.
     * Break x into its whole and fraction parts and
     * compute (e^(1 + fraction/whole))^whole using Taylor's formula.
     * @param x the value of x
     * @param scale the desired scale of the result
     * @return the result value
     */
    public static BigDecimal exp(BigDecimal x, int scale)
    {
        // e^0 = 1
        if (x.signum() == 0) {
            return BigDecimal.valueOf(1);
        }
    
        // If x is negative, return 1/(e^-x).
        else if (x.signum() == -1) {
            return BigDecimal.valueOf(1)
                        .divide(exp(x.negate(), scale), scale,
                                BigDecimal.ROUND_HALF_EVEN);
        }
    
        // Compute the whole part of x.
        BigDecimal xWhole = x.setScale(0, BigDecimal.ROUND_DOWN);
    
        // If there isn't a whole part, compute and return e^x.
        if (xWhole.signum() == 0) return expTaylor(x, scale);
    
        // Compute the fraction part of x.
        BigDecimal xFraction = x.subtract(xWhole);
    
        // z = 1 + fraction/whole
        BigDecimal z = BigDecimal.valueOf(1)
                            .add(xFraction.divide(
                                    xWhole, scale,
                                    BigDecimal.ROUND_HALF_EVEN));
    
        // t = e^z
        BigDecimal t = expTaylor(z, scale);
    
        BigDecimal maxLong = BigDecimal.valueOf(Long.MAX_VALUE);
        BigDecimal result  = BigDecimal.valueOf(1);
    
        // Compute and return t^whole using intPower().
        // If whole > Long.MAX_VALUE, then first compute products
        // of e^Long.MAX_VALUE.
        while (xWhole.compareTo(maxLong) >= 0) {
            result = result.multiply(
                                intPower(t, Long.MAX_VALUE, scale))
                        .setScale(scale, BigDecimal.ROUND_HALF_EVEN);
            xWhole = xWhole.subtract(maxLong);
    
            Thread.yield();
        }
        return result.multiply(intPower(t, xWhole.longValue(), scale))
                        .setScale(scale, BigDecimal.ROUND_HALF_EVEN);
    }
    
    double fraction, input;
    int base;
    double result;
    
    result = 0;
    base = n;
    input = x;
    
    while (input > base){
      result++;
      input /= base;
    }
    fraction = 1/2;
    input *= input;   
    
    while (((result + fraction) > result) && (input > 1)){
      if (input > base){
        input /= base;
        result += fraction;
      }
      input *= input;
      fraction /= 2.0;
     }
    
    public static BigDecimal log(int base_int, BigDecimal x) {
            BigDecimal result = BigDecimal.ZERO;
    
            BigDecimal input = new BigDecimal(x.toString());
            int decimalPlaces = 100;
            int scale = input.precision() + decimalPlaces;
    
            int maxite = 10000;
            int ite = 0;
            BigDecimal maxError_BigDecimal = new BigDecimal(BigInteger.ONE,decimalPlaces + 1);
            System.out.println("maxError_BigDecimal " + maxError_BigDecimal);
            System.out.println("scale " + scale);
    
            RoundingMode a_RoundingMode = RoundingMode.UP;
    
            BigDecimal two_BigDecimal = new BigDecimal("2");
            BigDecimal base_BigDecimal = new BigDecimal(base_int);
    
            while (input.compareTo(base_BigDecimal) == 1) {
                result = result.add(BigDecimal.ONE);
                input = input.divide(base_BigDecimal, scale, a_RoundingMode);
            }
    
            BigDecimal fraction = new BigDecimal("0.5");
            input = input.multiply(input);
            BigDecimal resultplusfraction = result.add(fraction);
            while (((resultplusfraction).compareTo(result) == 1)
                    && (input.compareTo(BigDecimal.ONE) == 1)) {
                if (input.compareTo(base_BigDecimal) == 1) {
                    input = input.divide(base_BigDecimal, scale, a_RoundingMode);
                    result = result.add(fraction);
                }
                input = input.multiply(input);
                fraction = fraction.divide(two_BigDecimal, scale, a_RoundingMode);
                resultplusfraction = result.add(fraction);
                if (fraction.abs().compareTo(maxError_BigDecimal) == -1){
                    break;
                }
                if (maxite == ite){
                    break;
                }
                ite ++;
            }
    
            MathContext a_MathContext = new MathContext(((decimalPlaces - 1) + (result.precision() - result.scale())),RoundingMode.HALF_UP);
            BigDecimal roundedResult = result.round(a_MathContext);
            BigDecimal strippedRoundedResult = roundedResult.stripTrailingZeros();
            //return result;
            //return result.round(a_MathContext);
            return strippedRoundedResult;
        }
    
    public int calculatePowersOf10(BigDecimal value)
    {
        return value.round(new MathContext(1)).scale() * -1;
    }
    
    import java.math.BigDecimal;
    import java.math.MathContext;
    
    public static long ITER = 1000;
    public static MathContext context = new MathContext( 100 );
    public static BigDecimal ln(BigDecimal x) {
        if (x.equals(BigDecimal.ONE)) {
            return BigDecimal.ZERO;
        }
    
        x = x.subtract(BigDecimal.ONE);
        BigDecimal ret = new BigDecimal(ITER + 1);
        for (long i = ITER; i >= 0; i--) {
        BigDecimal N = new BigDecimal(i / 2 + 1).pow(2);
            N = N.multiply(x, context);
            ret = N.divide(ret, context);
    
            N = new BigDecimal(i + 1);
            ret = ret.add(N, context);
    
        }
    
        ret = x.divide(ret, context);
        return ret;
    }
    
    public double log(BigInteger val)
    {
        // Get the minimum number of bits necessary to hold this value.
        int n = val.bitLength();
    
        // Calculate the double-precision fraction of this number; as if the
        // binary point was left of the most significant '1' bit.
        // (Get the most significant 53 bits and divide by 2^53)
        long mask = 1L << 52; // mantissa is 53 bits (including hidden bit)
        long mantissa = 0;
        int j = 0;
        for (int i = 1; i < 54; i++)
        {
            j = n - i;
            if (j < 0) break;
    
            if (val.testBit(j)) mantissa |= mask;
            mask >>>= 1;
        }
        // Round up if next bit is 1.
        if (j > 0 && val.testBit(j - 1)) mantissa++;
    
        double f = mantissa / (double)(1L << 52);
    
        // Add the logarithm to the number of bits, and subtract 1 because the
        // number of bits is always higher than necessary for a number
        // (ie. log2(val)<n for every val).
        return (n - 1 + Math.log(f) * 1.44269504088896340735992468100189213742664595415298D);
        // Magic number converts from base e to base 2 before adding. For other
        // bases, correct the result, NOT this number!
    }
    
    private static final double LOG10 = Math.log(10.0);
    
    /**
     * Computes the natural logarithm of a BigDecimal 
     * 
     * @param val Argument: a positive BigDecimal
     * @return Natural logarithm, as in Math.log()
     */
    public static double logBigDecimal(BigDecimal val) {
        return logBigInteger(val.unscaledValue()) + val.scale() * Math.log(10.0);
    }
    
    private static final double LOG2 = Math.log(2.0);
    
    /**
     * Computes the natural logarithm of a BigInteger. Works for really big
     * integers (practically unlimited)
     * 
     * @param val Argument, positive integer
     * @return Natural logarithm, as in <tt>Math.log()</tt>
     */
    public static double logBigInteger(BigInteger val) {
        int blex = val.bitLength() - 1022; // any value in 60..1023 is ok
        if (blex > 0)
            val = val.shiftRight(blex);
        double res = Math.log(val.doubleValue());
        return blex > 0 ? res + blex * LOG2 : res;
    }
    
    public double BigIntLog(BigInteger bi, double base) {
        // Convert the BigInteger to BigDecimal
        BigDecimal bd = new BigDecimal(bi);
        // Calculate the exponent 10^exp
        BigDecimal diviser = new BigDecimal(10);
        diviser = diviser.pow(bi.toString().length()-1);
        // Convert the BigDecimal from Integer to a decimal value
        bd = bd.divide(diviser);
        // Convert the BigDecimal to double
        double bd_dbl = bd.doubleValue();
        // return the log value
        return (Math.log10(bd_dbl)+bi.toString().length()-1)/Math.log10(base);
    }