Следующая функция автоматически преобразует вывод Solve
в список функций (при условии, что Solve
найдет решения, конечно):
solutionFunctions[expr_, var_] :=
Check[Flatten @ Solve[expr, var], $Failed] /.
(_ -> x_) :>
Function[Evaluate[Union @ Cases[x, _Symbol?(!NumericQ[#]&), Infinity]], x]
Вот пример:
In[67]:= g = solutionFunctions[x^2+a x+1==0, x]
Out[67]= {Function[{a},1/2(-a-Sqrt[-4+a^2])],Function[{a},1/2(-a+Sqrt[-4+a^2])]}
Функции можно вызывать по отдельности:
In[68]:= g[[1]][1]
Out[68]= 1/2 (-1-I Sqrt[3])
In[69]:= g[[2]][1]
Out[69]= 1/2 (-1+I Sqrt[3])
Или все функции можно вызывать сразу, чтобы вернуть все решения:
In[70]:= Through[g[1]]
Out[70]= {1/2 (-1-I Sqrt[3]),1/2 (-1+I Sqrt[3])}
Функция не будет выполнена, если Solve
не сможет найти решения:
In[71]:= solutionFunctions[Log[x]==Sin[x],x]
During evaluation of In[71]:=
Solve::nsmet: This system cannot be solved with the methods available to Solve.
Out[71]= $Failed
Переменные автоматически идентифицируются:
In[72]:= solutionFunctions[a x^2 + b x + c == 0, x]
Out[72]= { Function[{a, b, c}, (-b - Sqrt[b^2 - 4 a c])/(2 a)],
Function[{a, b, c}, (-b + Sqrt[b^2 - 4 a c])/(2 a)] }