Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

[Mathematica] NIntegrate Piecewise function with DE solution

  1. Feb 29, 2012 #1
    Hi,

    I'd like to solve a DE, create a function with the solution, then use that solution in a Piecewise function, and then NIntegrate the Piecewise function but I can't get NIntegate to work. Here's what I'm trying to do:

    Code (Text):

    mysol = NDSolve[{y'[x] == x, y[0] == 1}, y, {x, 0, 1}]
    myy[x_] := Evaluate[y[x] /. mysol];

    myf[x_] := Piecewise[{{myy[x], 0 < x <= 1}, {x^2, x > 1}}];

    NIntegrate[myf[x], {x, 0, 2}]
     
    NIntegrate then tells me it's not numeric in the interval.

    Can someone explain to me what I'm doing wrong?

    Thanks,
    Jack
     
  2. jcsd
  3. Feb 29, 2012 #2

    phyzguy

    User Avatar
    Science Advisor

    The output of NDSolve (mysol) is a list. You need to take the first element of it in your myy function definition, as follows:

    Code (Text):

    In[25]:= mysol = NDSolve[{y'[x] == x, y[0] == 1}, y, {x, 0, 1}]

    In[26]:= myy[x_] := Evaluate[y[x] /. mysol][[1]];

    In[27]:= myf[x_] := Piecewise[{{myy[x], 0 < x <= 1}, {x^2, x > 1}}];

    In[28]:= NIntegrate[myf[x], {x, 0, 2}]

    Out[28]= 3.5
     
     
  4. Feb 29, 2012 #3
    Ok. Thanks a bunch. It's working now. :)
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: [Mathematica] NIntegrate Piecewise function with DE solution
Loading...