Your code has three major flaws:
Since
a
,b
,c
,d
are numbers you cannot pass the stepk
to them. This syntax is for functions.Print[k]
should be used before changing the "the number of iterations" (k=k+1
) .Your code does not allow enough iterations to bracket the minimum (
n
is small).
You may also use internal Fibonacci
function, instead of manually enter
values for F
.
f[x_] := x^2 + 4*Cos[x];
FibonacciSearch[a0_, b0_, eps_] := Module[{a = N[a0], b = N[b0], n = 10},
k = 0;
While[(b - a) > eps,
frac = (Fibonacci[n - k + 1])/(Fibonacci[n - k + 2]);
c = a + (b - a) (1 - frac);
d = a + (b - a)*frac;
If[f[c] <= f[d],
b = d; k = k + 1;,
a = c; Print[{k, PaddedForm[a, {7, 6}], PaddedForm[b, {7, 6}]}]; k = k + 1;]
]
];
Run it as:
FibonacciSearch[1, 2, 0.01]
(* {9, 1.893569, 1.901699} *)
Indeed f[x]
has a minimum in the range $(1.893569, 1.901699)$,