csn899
(Lee Tao)
November 29, 2022, 12:03am
1
Solving the equation yields two:
Solve[x^2 + a x + 1 == 0, x]
{{x -> 1/2 (-a - Sqrt[-4 + a^2])}, {x -> 1/2 (-a + Sqrt[-4 + a^2])}}
How to automatically assign two values to two variables x1 and x2 after solving the equation
It is convenient to directly use variables x1 and x2 for other operations in subsequent calculations.
Use ReplaceAll
sol = Solve[x^2 + a x + 1 == 0, x]
{x1, x2} = x /. sol
x1
(* 1/2 (-a - Sqrt[-4 + a^2]) *)
x2
(* 1/2 (-a + Sqrt[-4 + a^2]) *)
eric3
(Eric Rimbey)
November 29, 2022, 4:28pm
3
You could skip a step by using SolveValues:
{x1, x2} = SolveValues[x^2 + a x + 1 == 0, x]
csn899
(Lee Tao)
December 4, 2022, 11:22am
4
the fuction solvevalues is in the new version of mathematica
csn899
(Lee Tao)
January 17, 2023, 2:42am
5
Further question: I want to assign a root greater than 0 to y1, and write the following code. Why is the result not what you want, and the calculated value of y1 less than 0? Why? How to rewrite the code?
ClearAll[Evaluate[Context[] <> "*"]]
eqns1 = {x^2/2^2 + y^2/1^2 == 1, y == x + 1};
{{x1, y1}, {x2, y2}} =
SolveValues[eqns1, {x, y}, Assumptions -> y1 > 0] // FullSimplify
the result is
{{-(8/5), -(3/5)}, {0, 1}}
Hi Lee
Assumptions -> y1 > 0 does nothing since y1 does not appear anywhere in the equations to be solved.
Is this what you are looking for?
{{x1, y1}} = SolveValues[eqns1, {x, y}, Assumptions -> y > 0]
y1
(* 1 *)
csn899
(Lee Tao)
January 17, 2023, 4:10am
7
I want to write all solution sets, but assign the value of y greater than 0 to y1, and other solutions will also be displayed.
eqns1 = {x^2/2^2 + y^2/1^2 == 1, y == x + 1};
{{x1, y1}} = SolveValues[eqns1, {x, y}, Assumptions -> y > 0]
{{x2, y2}} = SolveValues[eqns1, {x, y}, Assumptions -> y < 0]
This can solve the problem, but the code is awkward. Can you optimize it?
csn899
(Lee Tao)
January 17, 2023, 4:48am
8
There is also such a problem: if the equation has two solutions, compare the size of the two, assign the small root to y1, and assign the big root to y2, how to operate it?
as this eqns:
ClearAll[Evaluate[Context[] <> "*"]]
eqns1 = {x^2 - y == 0, y == x + 1};
{{x1, y1}, {x2, y2}} = SolveValues[eqns1, {x, y}]
csn899
(Lee Tao)
January 17, 2023, 10:46am
9
ClearAll[Evaluate[Context <> “*”]]
eqns1 = {x^2/2^2 + y^2/1^2 == 1, y == x + 1};
SolveValues[eqns1, {x, y}]
{{x1, y1}, {x2, y2}} = Sort[%, #1[[2]] < #2[[2]] &]
csn899
(Lee Tao)
January 17, 2023, 10:56am
10
Clear[“`*”]
eqns1 = {x^2/2^2 + y^2/1^2 == 1, y == x + 1};
SolveValues[eqns1, {x, y}]
{{x1, y1}, {x2, y2}} = Sort[%, #1[[1]] < #2[[1]] &]
Or
sol = SolveValues[eqns1, {x, y}]
{{x1, y1}, {x2, y2}} = SortBy[Last]
csn899
(Lee Tao)
January 18, 2023, 1:01am
12
there is something wrong with the result
Oops. I meant to write
{{x1, y1}, {x2, y2}} = sol // SortBy[Last]