" I have an assignment where I am required to use bisection or false position method depending on various inputs and I think I have a reasonable code that should work but I am not sure why I keep getting the errors at the bottom?"
----------
Func[f_, a_, b_, MaxIter_, eps_, flag_] := (
atable = {a};
btable = {b};
xtable = {1};
ErrorTable = {1};
i = 1;
Title = {"Iteration", "a", "b", "x_i", "f[a]", "f[b]", "f[x_i]", "er"};
T2 = Table[{i, atable[ [i]], btable[ [i]], xtable[ [i]], f[atable[ [i]]],
f[btable[ [i]]], f[xtable[ [i]]], ErrorTable[ [i]]}, {i, Length[xtable]}];
If[Or[flag < 1, flag > 2], "Please select appropriate values (1 or 2) for flag",
If[a > b, "Please select a < b",
If[f[a] * f[b] > 0, "Please select appropriate values a and b such that f[a]*f[b]<0",
While[And[i ≤ MaxIter, flag ⩵ 1],
ri = (atable[ [i]] + btable[ [i]]) / 2;
If[f[ri] * f[atable[ [i]]] ≤ 0, atable = Append[atable, atable[ [i]]];
btable = Append[btable, ri],
If[f[ri] f[btable[ [i]]] ≤ 0, btable = Append[btable, ri];
btable = Append[btable, btable[ [i]]]]];
If[i ⩵ 1, xtable[ [i]] = ri, xtable = Append[xtable, ri];
ei = N[ (xtable[ [i]] - xtable[ [i - 1]]) / xtable[ [i]]];
ErrorTable = Abs[Append[ErrorTable, ei]]];
If[Abs[ErrorTable[ [i]] < eps], flag ⩵ 0, flag ⩵ 1];
i ++];
While[And[i ≤ MaxIter, flag ⩵ 2],
ri = (atable * f[btable] - btable * f[atable]) / (f[btable] - f[atable]);
If[f[ri] * f[atable[ [i]]] ≤ 0, atable = Append[atable, atable[ [i]]];
btable = Append[btable, ri],
If[f[ri] f[btable[ [i]]] ≤ 0, btable = Append[btable, ri];
btable = Append[btable, btable[ [i]]];
If[i ⩵ 1, xtable[ [i]] = ri, xtable = Append[xtable, ri];
ei = N[ (xtable[ [i]] - xtable[ [i - 1]]) / xtable[ [i]]];
ErrorTable = Abs[Append[ErrorTable, ei]];
If[Abs[ErrorTable[ [i]] < eps], flag ⩵ 0, flag ⩵ 2];
i ++]]]]];
T2 = Prepend[T2, Title];
T2 // MatrixForm]])
f[x_] := x^3;
Func[f, -3, 7, 100, 0.001, 1]
----------
< Part: Part 3 of {-3, -3} does not exist.
Part: Part 3 of {-3, -3} does not exist.
Part: Part 3 of {-3., -3.} does not exist.
General: Further output of Part::partw will be suppressed during this calculation.>
Print[i]; Print[{atable,btable,xtable}]
right afterWhile[And[i ≤ MaxIter, flag == 1]
, it becomes clear that on the third iteration, atable's length is only two and the program requests its third element, thus raising the error. Also, I've noticed a typo: inIf[Abs[ErrorTable[[i]] < eps], flag == 0, flag == 1]
there must be = instead of ==. $\endgroup$ – aooiiii Feb 2 '20 at 9:26==
s in @miraj's code turned into a single unicode character⩵
that Mathematica doesn't recognize. If you replace them back, the errors return. Should have written that in the first comment, but ran out of allowed space. $\endgroup$ – aooiiii Feb 3 '20 at 5:23