Computer Science Canada

recursion

Author:  cool dude [ Sun Dec 03, 2006 4:42 pm ]
Post subject:  recursion

i have to make a program that using recursion to solve this problem. the problem is to determine the time it would take for your investment to double. The user will enter the initial deposit, the percent rate (interest), and the compound period i.e. every year.

the formula for compound interest is:
Quote:

Total = Principal x ( 1 + Rate )years


using this formula i keep calculating the total and adding a year everytime it calculates the total unil the total is equal to twice my intial investment.

EXAMPLE
Deposite: $5000
rate: 9%
compounded annually

Answer
It will take 8.0432 years for your investment to double.

I do not understand why my code isn't working. here is my function where i believe the error lies in. the rest of my code is not needed since its only asking the user for deposit, rate, and compound.

code:

        public static double Calculate (double deposit, double rate, int compound, double years, double goal)
        {       
                //investment = 0 thus no investment     
                if (deposit == 0)
                {
                        return years;
                }
                //doesn't reach goal of doubling investment yet
                if (deposit < goal)
                {
                        double total = deposit * Math.pow((1 + rate), compound);
                        years = years + (1 / compound);
                        return Calculate(total, rate, compound, years, goal);
                }
                //reached goal of doubling investment, return time it took
                else
                {
                        return years;
                }
        }

Author:  ericfourfour [ Sun Dec 03, 2006 5:03 pm ]
Post subject: 

code:
years = years + (1 / compound);

I have not ran your program but I don't think you should be assigning values to parameters. Instead use:
code:
return Calculate(total, rate, compound, years + (1 / compound), goal);

Author:  OneOffDriveByPoster [ Sun Dec 03, 2006 5:31 pm ]
Post subject:  Re: recursion

I sincerely doubt that you are being asked to provide an answer that is not a multiple of the compound period. Also, is the rate an APR?

Author:  cool dude [ Sun Dec 03, 2006 6:13 pm ]
Post subject: 

ahh i see what the problem is. at year 8 its not exactly doubled its only $9962.813208. Thus when it doubles it says its year 9 although it doubles between year 8 and 9. So how do i find the exact month? it should be 8.0432 years. in case you want to run the program here is a sample test.

code:

public class Investment
{
        public static void main (String [] args) throws IOException
        {
       System.out.println("\nThe Time it will take for investment to double is " + Calculate(5000, 0.09, 1, 0, 5450));
        }
       
        public static double Calculate (double deposit, double rate, int compound, double years, double goal)
        {       
                //investment = 0 thus no investment     
                if (deposit == 0)
                {
                        return years;
                }
                //doesn't reach goal of doubling investment yet
                if (deposit < goal)
                {
                        double total = deposit * Math.pow((1 + rate), compound);
                        return Calculate(total, rate, compound, years + (1 / compound), goal);
                }
                //reached goal of doubling investment, return time it took
                else
                {
                        return years;
                }
        }
}

Author:  wtd [ Sun Dec 03, 2006 10:36 pm ]
Post subject: 

code:
      if (deposit == 0)
      {
         return years;
      }
      //doesn't reach goal of doubling investment yet
      if (deposit < goal)
      {
         double total = deposit * Math.pow((1 + rate), compound);
         return Calculate(total, rate, compound, years + (1 / compound), goal);
      }
      //reached goal of doubling investment, return time it took
      else
      {
         return years;
      }


Small detail here...

code:
      if (deposit == 0)
      {
         return years;
      }
      //doesn't reach goal of doubling investment yet
      else if (deposit < goal)
      {
         double total = deposit * Math.pow((1 + rate), compound);
         return Calculate(total, rate, compound, years + (1 / compound), goal);
      }
      //reached goal of doubling investment, return time it took
      else
      {
         return years;
      }


Though, if we desire to get fancy about it...

code:
return (deposit < goal) ? Calculate(deposit * Math.pow(1 + rate, compound), rate, compound, years + 1 / compound, goal) : years;

Author:  cool dude [ Sun Dec 03, 2006 11:03 pm ]
Post subject: 

i rearanged the formula to be able to calculate for years by isolating years.

code:

        public static double Calculate (double deposit, double rate, double goal)
        {       
                double years = 0;
                //investment = 0 thus no investment     
                if (deposit == 0)
                {
                        return years;
                }
                        years = Math.log(goal/deposit)/Math.log(1+rate);
                        return years;
        }


it works very well now. but small problem. when i have interest compounded semi annualy (2 times) what i do is divide my rate by 2 and send it as the parameter, thus it should work. however i get the wrong result or atleast i think its wrong.

Sample Input
deposit: $5000
rate: 9%
commpounded: 2 (semi annually)

output
years: 7.8737

however the output i get is 15.74

Author:  ericfourfour [ Sun Dec 03, 2006 11:07 pm ]
Post subject: 

Or even fancier...
code:
return (deposit != 0  && (deposit < goal)) ? Calculate(deposit * Math.pow(1 + rate, compound), rate, compound, years + 1 / compound, goal) : years;

(removes need for first if)

Author:  cool dude [ Sun Dec 03, 2006 11:21 pm ]
Post subject: 

is my new way of rearanging the equation still using recursion?

Author:  zylum [ Sun Dec 03, 2006 11:23 pm ]
Post subject: 

try binary search:

psedocode:

fcn calculate (principal, rate, total)
        binSearch(principal, rate, total, 0, maxValue)
end calculate

fcn binSearch (p, r, t,  l,  u)
               
        if (abs(u - l) < epsilon) return l // where epsilon is how accurate
                                //you want your answer. try 1e-5 for example.
               
        mid = (l+u)/2;
               
        if (t > p*(1 + r)^mid) return binSearch(p, t, r, mid, u);
        else  return binSearch (p, t, r, l, mid);       

end binSearch

Author:  OneOffDriveByPoster [ Sun Dec 03, 2006 11:36 pm ]
Post subject: 

cool dude wrote:
i rearanged the formula to be able to calculate for years by isolating years.

Doesn't look recursive anymore though.
Answer is probably okay:
code:

deposit : $
rate : percent per unit time
compound per unit time

output : time in units time

=====

deposit : $5000.00
rate : 9% per year
compounded per 0.5 years

=====

deposit : $5000.00
rate : 4.5% per 0.5 years
compounded per 0.5 years

output : 15.7473 (0.5 years)

Author:  zylum [ Sun Dec 03, 2006 11:53 pm ]
Post subject: 

if you divide the rate by two, then it gives you the result as if it were still compounded anually, thus you should divide your output by 2.

Author:  cool dude [ Mon Dec 04, 2006 3:05 pm ]
Post subject: 

ha i just figured that out too zylum. before i saw your post. Smile
The point of this assignment is to use recursion to solve the problem so i'm not allowed to use binary search. Anyhow since this isn't using recursion i will get a zero so any ideas on how to make it recursive?

Author:  zylum [ Mon Dec 04, 2006 4:27 pm ]
Post subject: 

Laughing binary search is recursive. take a closer look at my pseudocode...

Author:  cool dude [ Mon Dec 04, 2006 4:33 pm ]
Post subject: 

zylum wrote:
Laughing binary search is recursive. take a closer look at my pseudocode...


yes i just found that out. I will be learning about binary search in a few days so i will know how to do it. sorry for my ignorance Sad

Author:  cool dude [ Mon Dec 04, 2006 5:39 pm ]
Post subject: 

This is annoying! I have to make a fibonacci program using recursion (Not allowed to use loops). i'm supposed to allow the user to enter the number of terms they want to view and then display all of them.

Here is how i made my program using recursion except for one problem. The problem is that it returns the value of the term itself and not of all the proceeding terms.

code:

import java.io.*;

public class Fibonacci
{
        public static void main (String [] args) throws Exception
        {
                int terms = 0;
                int ans = 0;
               
                BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));
               
                System.out.println("Enter number of terms to display");
                terms = Integer.parseInt(myInput.readLine());
               
                System.out.println("\n" + terms + " terms of Fibonacci numbers are:");
                System.out.println(Fib(terms));
        }
       
        public static int Fib(int n)
        {
                if (n<=2)
                {
                     return 1;
                }
                else
                {
                     return Fib(n-1) + Fib(n-2);
                }
        }
}

Author:  Andy [ Mon Dec 04, 2006 6:57 pm ]
Post subject: 

put the print inside the recursive function

Author:  gsquare567 [ Mon Dec 04, 2006 9:20 pm ]
Post subject: 

1.5 came out with the Scanner class, much better than the readers. but if this is for school, yeah, its probably still 1.4. damn school's slow updates.

Author:  cool dude [ Mon Dec 04, 2006 10:56 pm ]
Post subject: 

Andy wrote:
put the print inside the recursive function


I've actually been told the exact same thing by ultrahex. Here is the edited code all credit goes to ultrahex! However as you can probably see it works but it displays the fibonacci sequence backwards. I can obviously use a sort but that would be kinda cheating.

code:

import java.io.*;
 
public class Fibonacci
{
    public static void main (String[] args) throws Exception
    {
        int terms = 0;
        int ans = 0;
 
        BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));
 
        System.out.println ("Enter number of terms to display");
        terms = Integer.parseInt (myInput.readLine ());
 
        System.out.println ("\n" + terms + " terms of Fibonacci numbers are:");
        System.out.println (test (terms));
    }
 
    public static int test (int z)
    {
        System.out.println (Fib(z));
        if (z > 1)
        {
            test(z-1);
        }
        return 0;
    }
 
 
    public static int Fib (int n)
    {
 
        if (n <= 2)
        {
           //System.out.println (1);
            return 1;
        }
        else
        {
            //System.out.println (Fib (n - 1) + Fib (n - 2));
            return Fib (n - 1) + Fib (n - 2);
        }
    }
}

Author:  OneOffDriveByPoster [ Tue Dec 05, 2006 1:22 am ]
Post subject: 

If you are going to loop over with another function, it should be easy to fix...; however you can actually print inside Fib().
<pre>int fib(int n, bool print = true) {

int const ret = n <= 1 ? n == 1 : fib(n - 2, false) + fib(n - 1, print);
if (print) cout << ret << endl;
return ret;
}
</pre>

Author:  Aziz [ Tue Dec 05, 2006 9:26 am ]
Post subject: 

add each number onto a string perhaps

Author:  cool dude [ Tue Dec 05, 2006 5:55 pm ]
Post subject: 

Aziz wrote:
add each number onto a string perhaps


umm not sure what good that would do. only more work.

anyways i managed to get it in the right order and all. the only problem now is i keep getting a zero displaying at the end of my fibonacci sequence. It is because of this in my test method.
code:

return 0;


code:

import java.io.*;
 
public class Fibonacci
{
    public static void main (String[] args) throws Exception
    {
        int terms = 0;
        int ans = 0;
        int start = 0;
 
        BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));
 
        System.out.println ("Enter number of terms to display");
        terms = Integer.parseInt (myInput.readLine ());
 
        System.out.println ("\n" + terms + " terms of Fibonacci numbers are:");
        System.out.println (test (terms, start));
    }
 
    public static int test (int z, int start)
    {
        System.out.println (Fib(start));
        if (z > (start + 1))
        {
            return test(z,start + 1);
        }
        return 0;
    }
 
 
    public static int Fib (int n)
    {
 
        if (n < 2)
        {
           //System.out.println (1);
            return 1;
        }
        else
        {
            //System.out.println (Fib (n - 1) + Fib (n - 2));
            return Fib (n - 1) + Fib (n - 2);
        }
    }
}

Author:  gsquare567 [ Tue Dec 05, 2006 6:38 pm ]
Post subject: 

im not 100% sure, but i think after an int reaches its max value, it goes to the negatives where it is at its lowest point, and your method goes on infinitaly until that, so it eventually returns 0 once it reaches its max since u keep adding 1 to the variable.

Author:  cool dude [ Tue Dec 05, 2006 9:31 pm ]
Post subject: 

gsquare567 wrote:
im not 100% sure, but i think after an int reaches its max value, it goes to the negatives where it is at its lowest point, and your method goes on infinitaly until that, so it eventually returns 0 once it reaches its max since u keep adding 1 to the variable.


nope not at all! read my post i actually told you where my mistake is. i just don't know how to fix it.

Author:  OneOffDriveByPoster [ Wed Dec 06, 2006 12:44 am ]
Post subject: 

cool dude wrote:
code:

        System.out.println (test (terms, start));

Interesting, no?

Author:  cool dude [ Wed Dec 06, 2006 3:29 pm ]
Post subject: 

OneOffDriveByPoster wrote:
cool dude wrote:
code:

        System.out.println (test (terms, start));

Interesting, no?


hmm. not sure?

Author:  Andy [ Wed Dec 06, 2006 4:51 pm ]
Post subject: 

he was pointing out the vagueness of your variable names

Author:  cool dude [ Wed Dec 06, 2006 5:16 pm ]
Post subject: 

Andy wrote:
he was pointing out the vagueness of your variable names


ahh yes. the variable names are pretty bad. i'm going to be edditting a lot of the code format and putting in comments. i was just stuck on this problem so i kinda started making test methods and not caring about the format which i know is wrong to do. Sad


: