Arithmetic recursion

I am trying to write code that computes the following for a given integer n :

 1/1 + 1/2 + 1/3 ... + 1/n 

This is the code that I have written so far:

 public class RecursiveSum { public static double Sumto(int n) { if (n == 0) { return 0.0; } else if (n > 0) { return 1/n + 1/Sumto(n - 1); } else { throw new IllegalArgumentException("Please provide positive integers"); } } public static void main(String[] args) { System.out.println(Sumto(5)); } } 

However, it always outputs:

 Infinity 

What is the problem and how to fix it?

thanks

+6
source share
3 answers

You have two problems:

You must do floating point division (i.e. replace 1/n with 1.0/n ), and you must add Sumto(n - 1) to 1.0/n to get Sumto(n) .

  public static double Sumto(int n) { if (n == 0) { return 0.0; } else if (n > 0) { return 1.0/n + Sumto(n - 1); } else { throw new IllegalArgumentException("Please provide positive integers"); } } 

The reason you got Infinity was because 1/Sumto(n - 1) returns Infinity when Sumto(n - 1) is 0.0 and Sumto(0) is 0.0 .

+10
source

However, he always infers: Infinity

Since you are doing 1/0 in the next steps of the code that Infinity gives.

 else if (n > 0) { return 1/n + 1/Sumto(n - 1); 

You thought n > 0 avoids n / 0 products, but no! Think about the case where n = 1 , which goes through the case n > 0 , but falls into the trap:

 1/Sumto(n - 1) 1/Sumto(1 - 1) 1/Sumto(0) 

where Sumto(0) returns 0.0 . Hence,

  1/0.0 

gives Infinity . Also, use 1.0/n instead of 1/n , since this is a floating point separation .

So add another condition like

 if(n == 1) return 1; 
+2
source

A few problems, nothing in the first place, since there is no closed-form expression for a harmonic series.

  • You need to calculate each term using floating point division. Rewrite 1.0 / n .

  • Drop the term 1.0 / 0 as this will give you an infinite floating point value.

  • You will get better accuracy if you change the cycle. That is, first calculate the smaller terms. Otherwise, you will underestimate the amount with floating point arithmetic. As a rule, always add small numbers first.

0
source

All Articles