Click here to Skip to main content
15,887,861 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Trying to display the Fibonacci formula correctly with the correct nth values
Where nth would contain the correct value in the formula

Generally the formula used in this is -> [Fn = F(n-1) + F(n-2)]
I am trying to output the formula to show how I got the nth value like this ->[Fn = F(1-1) + F(2-2)]
and so on. But the values I used within the formula aren't calculating to the correct fibonacci number that is being output.

For example: I know Fn = F(1-1) + F(2-2) = 0, but if my output reads

Fn = F(1-1) + F(1-2) = 1
Fn = F(1-1) + F(1-2) = 1
Fn = F(2-1) + F(2-2) = 2
Fn = F(3-1) + F(3-2) = 3

Then these forumlas are incorrect and do not equal the fibonacci value thats been output.


C#
public static int F(int n) 
        {
            // Return Fibonacci number, 0 first, second # = 1
            if (n == 0 || n == 1)
                return n; 
            else
                // Fibonacci Formula
                return F(n - 1) + F(n - 2); 
        }

        private void btnStartStop_Click(object sender, EventArgs e)
        {
            try
            {
                // Integer indicates start of Series, first element = 0
                int i;

                /* How many elements will be displayed.
                 * Max 20. Any elements higher than 20
                 * will increase load on cpu. Possible
                 * for 40 elements but only on faster
                 * processors */
                int length = Int32.Parse(txtFibSeriesLength.Text);

                //Loop until all elements have been processed                 
                for ( i= Int32.Parse(txtFibFirst.Text); i < length; i++)
                {
                    // Show results in output window. F(i) processes formula and returns Fibonacci int
                    if (F(i) > 0 )
                        txtOutput.Text = txtOutput.Text + "Fn = F(" + F(i) + "-1) + F(" + F(i) + "-2) = " + F(i) + Environment.NewLine;                       
                }       
            }
            catch (Exception error) // Catch exception if thrown
            {   
                MessageBox.Show(error.Message);// Throw error if invalid string or no string
            };            
        }
Posted
Updated 24-Sep-15 4:45am
v2
Comments
[no name] 24-Sep-15 4:17am    
What problem you are facing here?
Richard MacCutchan 24-Sep-15 4:18am    
What is the question?

Your output is wrong - instead of writing:
F(n) = F(n - 1) + F(n - 2)

you're writing:
F(n) = F(F(n) - 1) + F(F(n) - 2)


You should also cache the result of F(i), since you're using such an inefficient way to calculate it.

Consider using string.Format to make your code more readable.
C#
int result = F(i);
if (result > 0)
{
    txtOutput.Text = txtOutput.Text + string.Format("F(n) = F({0}-1) + F({0}-2) = {1}", i, result) + Environment.NewLine;
}


EDIT:
Based on your deleted comment, you're looking for something like this:
C#
int length;
if (!int.TryParse(txtLengthOfSeries.Text, out length))
{
    MessageBox.Show("Please enter a valid length!");
    txtLengthOfSeries.Focus();
    return;
}

int term1, term2 = 1, fib = 0;
for (int i = 0; i < length; i++)
{
    term1 = term2;
    term2 = fib;
    fib = term1 + fib;
    
    if (i < 2)
    {
        txtOutput.Text += string.Format("F({0}) = {1}\n", i, fib);
    }
    else
    {
        txtOutput.Text += string.Format("F({0}) = F({1}) + F({2}) = {3}\n", i, i - 1, i - 2, fib);
    }
}
 
Share this answer
 
v2
Comments
Herboren 24-Sep-15 11:43am    
As much as the string.Format cleaned it up, that helped, but the formula does not equate to the Fibonacci value when output. Results:

F(n) = F(1-1) + F(1-2) = 1
F(n) = F(2-1) + F(2-2) = 1
F(n) = F(3-1) + F(3-2) = 2
F(n) = F(4-1) + F(4-2) = 3
Richard Deeming 24-Sep-15 11:46am    
1, 1, 2, 3 is the start of the Fibonacci sequence. I don't see any problem with the output you've posted.
Herboren 24-Sep-15 12:02pm    
Within F(n) = F(1-1) + (1-2) does not equal to 1
Within F(n) = F(3-1) + F(3-2) does not equal to 2

F(n) = F(1-1) + (1-2) equals to -1
F(n) = F(3-1) + F(3-2) equals to 3

So where 1,1,2,3.. is the correct sequence when output, the formula values are not.
Richard Deeming 24-Sep-15 12:08pm    
First of all, the Fibonacci sequence is not defined for numbers less than zero, so F(1 - 2) makes no sense.

The definition that you're using is:
F(0) = 0
F(1) = 1
F(n : n > 1) = F(n - 1) + F(n - 2)


Therefore, F(1) = 1, which is correct. It's just the way you're displaying it that's confusing you.

F(3) = F(2) + F(1) = F(1) + F(0) + F(1) = 1 + 0 + 1 = 2
So F(3) = 2 is correct.

In all of the examples you've given, the "formula values" are correct.

You've confused yourself by starting the sequence with 0.
Herboren 24-Sep-15 12:33pm    
Prolly not asking this in the right place, what does n-1 mean, if you are just plugging the term into F(3) + F(5) = 8
Um...
Fibonaci sequence:
1 1 2 3 5 8 ...

But this code:
C#
if (n == 0 || n == 1)
    return n;

Generates the sequence
0 1 1 2 3 5 ...

Try:
C#
if (n == 0 || n == 1)
    return 1;


However, the way you are doing it is very inefficient: you generate most of the sequence twice in order to generate F[4], because you recurse twice on n-1 and n-2.

I wouldn't use recursion for this: a simple loop would be a lot quicker and more efficient!
 
Share this answer
 
Comments
Richard Deeming 24-Sep-15 11:04am    
Apparently, using F(0) = 0 is an acceptable form of the sequence these days:
Fibonacci number - Wikipedia[^]
I fixed it by removing theseparate function and just including it in the button down:
C#
int Term1 = 0, Term2 = 1, ReturnTerm = 0, i;
           for (i = 0; i < Int32.Parse(txtLengthOfSeries.Text); i++)
           {
               Term1 = Term2; Term2 = ReturnTerm; ReturnTerm = Term1 + ReturnTerm;
               txtFibonacciOutput.Text = txtFibonacciOutput.Text + string.Format("F({0}) = F({1})+F({2}) = {3}", i,Term1, Term2, ReturnTerm) + Environment.NewLine;
           }
 
Share this answer
 
v4
Comments
Richard Deeming 24-Sep-15 14:49pm    
That's still not right. In the string.Format call, you need to pass i - 1 instead of Term1, and i - 2 instead of Term2.

With the code you've posted, the output will be wrong from F(5) onwards:
F(5) = F(3) + F(5)
F(6) = F(5) + F(8)
F(7) = F(8) + F(13)
...


It should be:
F(5) = F(4) + F(3)
F(6) = F(5) + F(4)
...
Herboren 24-Sep-15 16:32pm    
Which is exactly what I asked several times earlier. I kept asking, which numbers are being plugged into the n values, or how can I display what numbers are plugging into those values, in the full formula that the user can see. I can get the Fibonacci answers without problems, this is easy, it is the Formula I want to show the end user how the answer was found. I am trying to display the whole formula as the answer itself, what it would look like if it was written on paper. And the correction that you guys gave me is still producing the wrong formula with the incorrect 'n-1; n-2' results, which does not provide that right answer if worked left to right. I have written the produced formulas on paper and they DO NOT equate. I have shown the output several times with all of your code corrections in a compiled format and still does not produce the result that it should. I am not trying to sound like frustrated really, I know you guys are amazing at what you do and I couldn't begin to compare, but I know it's mostly my perspective that you don't see. I'll try my best to esplain what I want the end user to see.

This is what the end user should see in the text window after press a button:

F(0) = F((a number, not n) - 1) + F((a number, not n) - 2) = 0
F(1) = F((a number, not n) - 1) + F((a number, not n) - 2) = 1
F(2) = F((a number, not n) - 1) + F((a number, not n) - 2) = 1
F(3) = F((a number, not n) - 1) + F((a number, not n) - 2) = 2
F(4) = F((a number, not n) - 1) + F((a number, not n) - 2) = 3
F(5) = F((a number, not n) - 1) + F((a number, not n) - 2) = 5

Instead of seeing after pressing a Button

F(0) = 0
F(1) = 1
F(2) = 2
F(3) = 3
F(4) = 5
F(5) = 8

The goal is, I should be able to explain to someone how the operation is performed, rather than giving the answer. I guess you could say step by step operation. So not only than give the computer the formula produce and answer, but use the computer to also explain how the answer was produced by using the Fibonacci formula directly.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900