0

I am a beginner to Java and now learned about recursion. As a first exercise problem I tried to solve the approximation of PI by the foollowing method:

Algorithm for pi

I tried to solve it and my first solution just rounded every value to 0 (which I could see by adding a print Statement). As soon as I changed the argument type for the function from int n to double n (just random trying out), it suddenly would start approxiatong PI. Im very confused, why does that solution actually work, the values put into the argument are always integers, right? So why does it make a difference? Appreciate every answer, thanks!

public static double Pi_app(double n //I initially set this to int n, which didnt work) {
 double pi_app=0;
    if(n>=0) {
        
        if(n%2==0) {
            pi_app=(4/(2*n+1))+Pi_app(n-1);
        }
        else pi_app=(-4/(2*n+1))+Pi_app(n-1);  
    }   
return pi_app;}

0 Answers0