Matlab/Octave斐波那契函数求助:修复序列缺失1的问题
Let's break down the issue and fix your recursive Fibonacci function step by step.
The Core Problem
Your current rtfib generates a shifted sequence because its base cases (termination conditions) don't align with the standard Fibonacci definition. The standard sequence follows:
- F(0) = 0
- F(1) = 1
- F(n) = F(n-1) + F(n-2) for n ≥ 2
Your function returns F(2)=2 instead of 1, which means it incorrectly treated F(2) as a base value instead of calculating it from F(1) and F(0).
Fixed Code
Here's the corrected version, with fixes for both base cases and negative number handling (your original negative sign logic was incomplete):
function f = rtfib(n) multi = 1; if n < 0 % Correct sign for negative Fibonacci terms: F(-n) = (-1)^(n+1)*F(n) multi = (-1)^(abs(n) + 1); n = abs(n); end % Standard base cases for Fibonacci sequence if n == 0 f = 0; elseif n == 1 f = 1; else % Recursive calculation using standard recurrence relation f = rtfib(n-1) + rtfib(n-2); end % Apply sign multiplier for negative inputs f = f * multi; end
Key Fixes Explained
Corrected Base Cases:
We only usen=0 → 0andn=1 →1as base cases. For n≥2, we calculate the value by summing the two preceding terms—this directly fixes the missing1at n=2 and aligns all subsequent values to the standard sequence.Proper Negative Number Handling:
The original code used a simplemulti=-1, which doesn't account for the alternating sign of negative Fibonacci terms. The correct formula isF(-n) = (-1)^(n+1)*F(n), so we compute the multiplier as(-1)^(abs(n)+1)to get the right sign for any negative input.
Testing the Fixed Function
Verify outputs match the standard sequence:
rtfib(0)→ 0 ✔️rtfib(1)→ 1 ✔️rtfib(2)→ 1 ✔️rtfib(3)→ 2 ✔️rtfib(4)→ 3 ✔️rtfib(5)→5 ✔️
For negative inputs, you'll also get correct results:
rtfib(-1)→1 ✔️rtfib(-2)→-1 ✔️rtfib(-3)→2 ✔️
内容的提问来源于stack exchange,提问作者Rick T

