0

I am encountering some error while trying to find roots of equation using Bisection method. In this method, you take an interval (a1,b1), here I have taken (0,1). If f(a1)f(b1)<0, then you take p1 =average of a1,b1. And depending on its sign, replace one of a1 or b1 by p1 to get a2,b2 and then you repeat, getting closer to the value of root of the equation. Aim of the code is to get as many values of ai,bi,pi as we want for required approximation.

f[x_] := Log[1 + x] - Cos[x]
a[1] = 0;
Sign[f[a[1]]]
b[1] = 1;
Sign[f[b[1]]]
p[i] = -1;
For[i = 1, i <= 4, i++, 
 If[f[a[i]]*f[b[i]] < 0, Print[a[i], " and ", b[i]]
    p[i] = (a[i] + b[i])/2
    If[Sign[f[p[i]]] == Sign[f[a[i]]], a[i + 1] = p[i]
        b[i + 1] = b[i], b[i + 1] = p[i] 
        a[i + 1] = a[i]], 
  Print["Completed ", i, "iterations. Last iteration:No root found"]]]

Somehow the code is not executing. I am getting Set::write: Tag Times in 1/2 Null If[Sign[-Cos[<<1>>]+Log[Plus[<<2>>]]]==-1,a[i+1]=p[i] b[Plus[<<2>>]]=b[i],b[i+1]=p[i] a[Plus[<<2>>]]=a[i]] is Protected. >>

Also, in 8th line, if I add p[i] along with a[i],and b[i] in the print statement, the error gets worse. So I cant even print pi inside the loop.

Please help. I am an amateur and it most probably is just a basic syntax mistake, but I am new to mathematica and I've spent 2 hours on this with no avail. Thanks!

1 Answers1

0

If you look at the code in Mathematica 12, you'll see the faint xs (multiplication sign, not an 'ex') at the end of some lines. These are actually hints to the user that there might be an unexpected multiplication happening in your code. To fix this, you'll want to add semi-colons after the individual lines where the x's are.

enter image description here

I am not sure if this is "correct" in terms of the results, but it no longer emits errors:

f[x_] := Log[1 + x] - Cos[x]
a[1] = 0;
Sign[f[a[1]]]
b[1] = 1;
Sign[f[b[1]]]
p[i] = -1;
For[i = 1, i <= 4, i++, 
 If[f[a[i]]*f[b[i]] < 0, Print[a[i], " and ", b[i]];
    p[i] = (a[i] + b[i])/2;
    If[Sign[f[p[i]]] == Sign[f[a[i]]], a[i + 1] = p[i];
        b[i + 1] = b[i], b[i + 1] = p[i] ;
        a[i + 1] = a[i]], 
  Print["Completed ", i, "iterations. Last iteration:No root found"]]]

There are most certainly errors elsewhere in your code that you'll need to work out to get the correct answer for your numeric algorithm, however.

ktm
  • 4,242
  • 20
  • 28