This week's book giveaway is in the Cloud/Virtualizaton forum.We're giving away four copies of Mesos in Action and have Roger Ignazio on-line!See this thread for details.
Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# math question (natural log - ln)

Tom Clement
Greenhorn
Posts: 26
Hi, working on a project which must calculate natural logarithms,
I see calculators do it all over, but my luck with source code evaluation hasn't turned up what I need.

Example:
ln 27 = 3.29583686600432907418573571076758

Must be a relatively easy way to do it, closest I came was the rounded 3:

with the following code

import java.math.*;
public class Test2 {

static double xDouble;

public static void main(String[] args) {

double d = 1.0;

BigInteger target = BigInteger.valueOf(27);

target = doLog(target,d);
System.out.println(target);
}

static public BigInteger doLog (BigInteger target, double divisor)
{

xDouble = logBig(target.abs())/divisor;

return BigInteger.valueOf((long)(xDouble));
}

static public double logBig(BigInteger z) {
// Needed because Math.log(z.doubleValue()) returns infinite for z bigger than MAX DOUBLE
BigInteger b;
int temp = z.bitLength() - 1000;
if (temp > 0) {
// b=z.divide(BigInteger.valueOf(2).pow(temp)); //replaced with below
b=z.shiftRight(temp);
return (Math.log(b.doubleValue()) + temp*Math.log(2));
}
else {return (Math.log(z.doubleValue()));}
}
}

Many thanks......................Tom
[ February 26, 2005: Message edited by: Tom Clement ]

M Beck
Ranch Hand
Posts: 323
you're seeing your results rounded to the nearest integer value because you're storing them in a BigInteger variable. have you tried using BigDecimal instead?

Tom Clement
Greenhorn
Posts: 26
No, I haven't yet, I'll try it now, thanks

Tom Clement
Greenhorn
Posts: 26
tried BigDecimal, it's not a straightforward swap, it'll take more time than I
have tonight, I'll definitely try tomorrow. With all those calculators out there, I'm hoping someone's done this already.

David Harkness
Ranch Hand
Posts: 1646
Why can't you use java.lang.Math.log(double)? Since you're taking the double value of your BigInteger (and eventually BigDecimal), why bother with those classes at all?

Layne Lund
Ranch Hand
Posts: 3061
As their names imply, BigInteger and BigDecimal are meant to be used for arbitrarily large numbers. Unless, you are using numbers that are over 9*10^19 (the maximum value for a long), then you should probably just use the built-in types like double and long. The Math class from the standard API provides methods to perform just about any mathematical operation you need. These include the basic trigonometric functions and logarithms, to name a few.

HTH

Layne

Ilja Preuss
author
Sheriff
Posts: 14112
Somehow this discussion seems to be continued at http://www.coderanch.com/t/326805/java/java/natural-logarithms-ln