Mathematica Asked by Bananach on July 5, 2021
I have a complicated expression that contains N variables.
I want to create a function of N-1 that solves for one of those variables
Toy example:
expr = a^2-Sin[a*b]
astar[b_] := NSolve[expr==0, a, Reals]
astar[1]
does not work. I hoped it was equivalent to
NSolve[(expr/.{b->1})==0,a, Reals]
which does work.
I also tried
expr = a^2-Sin[a*b]
astar[b_] := NSolve[(expr/.{b->b})==0, a, Reals]
astar[1]
but that also doesn’t work.
Functions should have explicit parameters.
expr[a_, b_] = a^2 - Sin[a*b];
Functions that use numeric techniques should restrict their parameters to numeric values.
astar[b_?NumericQ] := NSolve[expr[a, b] == 0, a, Reals];
astar[1]
(* {{a -> 0.}, {a -> 0.876726}} *)
Alternatively, get the exact solution
astar2[b_] := Solve[expr[a, b] == 0, a, Reals];
The exact solution is expressed as a Root
expression
(* {{a -> 0},
{a -> Root[{-Sin[#1] + #1^2 & ,
0.8767262153950624459721623939201240
4608`20.315993684930827}]}} *)
Its approximate numeric value is the same as provided by astar
% // N
(* {{a -> 0.}, {a -> 0.876726}} *)
Answered by Bob Hanlon on July 5, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP