1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Mathmatica Bisection Root Finding

  1. Sep 14, 2014 #1
    1. The problem statement, all variables and given/known data

    Write code in Mathematica to find the root of

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

    using the bisection method.

    I have attempted to do this using:
    Code (Text):

    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.
     
  2. jcsd
  3. Sep 14, 2014 #2
    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 lets 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.
     
  4. Sep 14, 2014 #3
    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.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted