Forgive me if this doesn’t sound very good, I am not the best at English. My code so far is this: even though I’m aware that I’ve done most wrong. I know it is wrong but I can not find out where to start or how to change the sign. I was at first doing this thinking we needed to find the ln of different numbers but later learned it was with input n. EDIT: I believe I know what major part I was doing wrong. I fixed this to the best of my ability. I’m now a bit stuck because I’m playing out the logic in my head and I believe it should work. Instead all it prints out is 1.0 1.0 1.0 1.0 1.0
Can anyone help point out what I am doing wrong?
public class aprox_log {
static double findLog (int n)
{
double ln = 1;
for (int i = 1; i <= n; i++)
{
for (int k = 0; i <= n; k++) {
if ((k%2) == 0)
ln = ln - (1/i);
ln = ln + (1/i);
}
}
return 1 - ln;
}
public static void main(String[] args) {
//These lines print the results of test inputs.
System.out.println(findLog(2)); //~0.69314718056
System.out.println(findLog(5)); //~1.60943791243
System.out.println(findLog(10)); //~2.30258509299
System.out.println(findLog(9)); //~2.19722457734
System.out.println(findLog(1)); //0
}
}
NEW CODE:
public class aprox_log {
static double findLn (int n)
{
double ln = 0;
for (int i = 1; i <= n; i++)
{
if (i%2 == 0)
ln = ln - (1/i);
ln = ln + (1/i);
}
return ln;
public static void main(String[] args) {
//These lines print the results of test inputs.
System.out.println(findLn(2)); //0.5
System.out.println(findLn(5)); //0.783333333
System.out.println(findLn(10)); //0.64563492063
System.out.println(findLn(9)); //0.74563492063
System.out.println(findLn(1)); //1
}
}
`
Advertisement
Answer
To find the sum of the alternating harmonic series with n
terms, just loop over the integers from 1 to n
. Then, add the reciprocal of the current number if it is odd and subtract the reciprocal if it is even.
static double findLog(int n){
double res = 0;
for(int i = 1; i <= n; i++) res += 1d / (i % 2 == 0 ? -i: i);
return res;
}