I know I could generate it using Math.log(2)
but I when I try to make up my own program to generate a natural log of 2 it continuously print 1. This is my code:
import java.math.BigDecimal;
import java.util.Scanner;
public class Ques11 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
BigDecimal sum = new BigDecimal(1);
for(int i = 2; i <= n; i++) {
sum.add(new BigDecimal(1/n));
}
System.out.print(sum.setScale(10).toPlainString());
}
}
I have tried to use float
, double
and int
and in the end used BigDecimal
but I still got 1 as the result I don't know why.
P.S It actually throws InputMismatchException
when big numbers are given i.e greater than 2000000000
or 2 Billion
.