Mathematica: building a module with FindRoot in it

I sometimes run into this problem and I have not found a way around it. This usually happens when I find the root of the equation and want to maximize / minimize / build this root according to some parameter. Therefore, I am trying to wrap the code in a module so that it can only be executed with an input number, but it will not work inside functions like Plot. For instance:

f[din_] := Module[{d = din}, sol = NDSolve[{y'[x] == y[x], y[0] == 1}, y[x], {x, 0, 10}]; t1 = Flatten[FindRoot[y[x] - d /. sol, {x, 1}]]; x /. t1 ] f[2] f[2.5] f[3] Plot[f[x], {x, 2, 3}] 

Calling f with the number all works as expected, but the f function in the Plot function is apparently evaluated by the character "x", or something, and just gives a lot of error text.

How to get around this?

Looking back at the forums, I found several suggestions for similar problems - for example, making the definition as follows:

  f[din_?NumericQ]:= 

and I tried everything I could, but nothing changed. I am using Mathematica 8.0

+4
source share
2 answers

The main solution is to derive sol = NDSolve[... from the module. The module itself can also be simplified, as shown: -

 sol = NDSolve[{y'[x] == y[x], y[0] == 1}, y[x], {x, 0, 10}]; f[din_] := x /. FindRoot[y[x] - din /. sol, {x, 1}] Plot[f[x], {x, 2, 3}] 

enter image description here

+1
source

Try:

 f[din_?NumericQ] := Module[{LocalDummy, Localy, LocalSol}, Localy = y /. NDSolve[{y'[LocalDummy] == y[LocalDummy], y[0] == 1}, y, {LocalDummy, 0, 10}][[1]]; LocalSol = FindRoot[Localy[LocalDummy] - din == 0, {LocalDummy, 1}][[1, 2]] ] 

plot

0
source

Source: https://habr.com/ru/post/1433071/


All Articles