In: Computer Science
In Java!!
Problem 2 – Compute the sum of the series (19%)
The natural logarithm of 2, ln(2), is an irrational number, and can be calculated by using the following series:
1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 + 1/7 - 1/8 + ... 1/n
The result is an approximation of ln(2). The result is more
accurate when the number n goes larger.
Compute the natural logarithm of 2, by adding up to n terms in the
series, where n is a positive integer and input by user.
Requirements:
Use either for or while loop to display the number pattern.
CODE
==============
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new
Scanner(System.in);
int n;
System.out.println("Enter the
number of terms in the series: ");
n = sc.nextInt();
double sum = 0;
for (int i = 1; i<=n; i++)
{
double term =
1.0/i;
if (i % 2 == 0)
{
sum -= term;
} else {
sum += term;
}
System.out.println("Term " + i + " = " + term);
}
System.out.println("ln(2) = " +
sum);
}
}