You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matlab/Octave斐波那契函数求助:修复序列缺失1的问题

Fixing the rtfib Function for Standard Fibonacci Sequence

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

  1. Corrected Base Cases:
    We only use n=0 → 0 and n=1 →1 as base cases. For n≥2, we calculate the value by summing the two preceding terms—this directly fixes the missing 1 at n=2 and aligns all subsequent values to the standard sequence.

  2. Proper Negative Number Handling:
    The original code used a simple multi=-1, which doesn't account for the alternating sign of negative Fibonacci terms. The correct formula is F(-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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:14:54