# Finding log() without using Math.log()

Finding log for any given base and value in JAVA

``````
import java.util.Scanner;

public class LogSolution {
static int scaleSize=1000000;
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
double b = in.nextDouble();
double T = in.nextDouble();

//As per Logarithmic base change rule
System.out.println(Math.log(T) / Math.log(b));

//Logarithm without Math.log() API
System.out.println(log(b, T, 0));

}

private static double log(double base, double n, double log) {

if (n == 1)
return 0;

if (n < base) {
//Log base switch rule
return 1 / log(n, base, log);
}
double value = 1;
do {
value *= base;
log++;
} while (value < n);

if (value == n) {
return log;
}

log--;
return log(base, n, log, 1);
}

private static double log(double base, double n, double log,
double precision) {
double newPrecision = precision * 0.1d;

double prevLog = log;
for (int i = 1; i <= 10; i++) {
double newLog = log + (i * newPrecision);
double n2 = Math.pow(base, newLog);

if (n == n2)
return newLog;

if (n < n2) {
if (1 != (int) (newPrecision * scaleSize))
return log(base, n, prevLog, newPrecision);
else
return prevLog;
}
prevLog = newLog;
}

return log;
}
}``````

### Logarithm rules

```Logarithm product rule

logb(x × y) = logb(x) + logb(y)

Logarithm quotient rule

logb(x / y) = logb(x) - logb(y)

Logarithm power rule

logb(x ^ y) = y × logb(x)

Logarithm base switch rule

logb(c) = 1 / logc(b)

Logarithm base change rule

logb(x) = logc(x) / logc(b)
```

RapidTables |
MATHisFUN