Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 recursion
Index -> Programming, Java -> Java Help
Goto page 1, 2  Next
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
cool dude




PostPosted: 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;
                }
        }
Sponsor
Sponsor
Sponsor
sponsor
ericfourfour




PostPosted: Sun Dec 03, 2006 5:03 pm   Post subject: (No 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);
OneOffDriveByPoster




PostPosted: 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?
cool dude




PostPosted: Sun Dec 03, 2006 6:13 pm   Post subject: (No 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;
                }
        }
}
wtd




PostPosted: Sun Dec 03, 2006 10:36 pm   Post subject: (No 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;
cool dude




PostPosted: Sun Dec 03, 2006 11:03 pm   Post subject: (No 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
ericfourfour




PostPosted: Sun Dec 03, 2006 11:07 pm   Post subject: (No 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)
cool dude




PostPosted: Sun Dec 03, 2006 11:21 pm   Post subject: (No subject)

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




PostPosted: Sun Dec 03, 2006 11:23 pm   Post subject: (No 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
OneOffDriveByPoster




PostPosted: Sun Dec 03, 2006 11:36 pm   Post subject: (No 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)
zylum




PostPosted: Sun Dec 03, 2006 11:53 pm   Post subject: (No 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.
cool dude




PostPosted: Mon Dec 04, 2006 3:05 pm   Post subject: (No 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?
zylum




PostPosted: Mon Dec 04, 2006 4:27 pm   Post subject: (No subject)

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




PostPosted: Mon Dec 04, 2006 4:33 pm   Post subject: (No 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
cool dude




PostPosted: Mon Dec 04, 2006 5:39 pm   Post subject: (No 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);
                }
        }
}
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 2  [ 27 Posts ]
Goto page 1, 2  Next
Jump to:   


Style:  
Search: