Mathmatica Bisection Root Finding

  • Thread starter Thread starter teroenza
  • Start date Start date
  • Tags Tags
    Root
AI Thread Summary
The discussion focuses on implementing the bisection method in Mathematica to find the root of the function f(x) = ∫(sin(t)/t) dt - π/2. The user initially encounters a "Tag Times" error due to missing semicolons and incorrect function definition. After adding semicolons, the error is resolved, but the loop fails to terminate correctly. It is identified that the stopping condition should use the x point instead of f(x) for proper convergence. The conversation emphasizes the importance of syntax and correct logic in programming within Mathematica.
teroenza
Messages
190
Reaction score
5

Homework Statement



Write code in Mathematica to find the root of

f(x) = \int_0^x \frac{\sin (t)}{t} \, dt-\frac{\pi }{2}

using the bisection method.

I have attempted to do this using:
Code:
f[x_] := N[-(Pi/2) + Integrate[Sin[t]/t, {t, 0, x}]]
(*Plot[f[x],{x,0,2*Pi}]*)
fg = f[1.5](*initial guess evaluation*)
r1 = FindRoot[f[x], {x, 1.5}];(*Mathmatica's guess for the root*)
r1 = r1[[1, 2]]
xg = 1.5; xn = 1; xp = 3; (*Initialize guess point, and bracket to \
search over*)

While[Abs[fg - r1]/r1*100 > 0.1,
 (*continue while deviation from Mathematica's root is > 0.1*)
 
 If[fg > 0,(*update bounds*)
    xp = xg,(*old guess is new upper root bound*)
    xn = xg(*old guess is new lower root bound*)
    ]
   
   xg = (xn + xp)/2(*Bisect interval to generate new guess point*)
    Print[fg]
    fg = f[
    xg](*update the function's value to feed back into the while \
condition*)
 
 ]

But I keep getting errors such as ""Tag Times in -0.246113\ 2\ Null is Protected."". I am trying to figure out if I defined the function incorrectly, or am missing something else.
 
Physics news on Phys.org
Add a semicolon to the end of each of your separate statements. Yes Mathematica can sometimes let you skip putting in a semicolon, but too often that will get you into trouble. Mathematica also let's you omit the * to indicate multiplication and often just assumes two things next to each other are to be multiplied. That is probably the source of your "Tag Times" error, it thinks you are trying to multiply a couple of statements together.

When I add those that error goes away and your loop appears to converge, but it doesn't seem to stop appropriately.

See if you can get this far and then try to decide why it isn't stopping.
 
Interesting, thank you. I was using semicolons to suppress output to the screen, and I wasn't sure if they would interfere with the syntax within the loop statements. I didn't bother to use it on (suppress) the ones in the loops before.

I also see why it was not stopping. It should have been the x point, not the f(x) point, that was being used in as the condition for the while loop.
 

Similar threads

Back
Top