I have the following problem in Mathematica:
values = {b -> 1, c -> 0};
Solutions := Solve[x^2 + b*x + c == 0, x]
x1 := x /. Solutions[[1]];
x2 := x /. Solutions[[2]];
"Solution 1"
x1
"Solution 2"
x2
"Choose ~preferred~ Solution, which is -1 when using values"
If[Module[{list = values}, ReplaceRepeated[x1 == -1, list]], x = x1, x = x2]
"~Preferred~ Solution"
x
When I evaluate it the first time,everything works:
Solution 1
1/2 (-b - Sqrt[b^2 - 4 c])
Solution 2
1/2 (-b + Sqrt[b^2 - 4 c])
Choose ~preferred~ Solution, which is -1 when using values
1/2 (-b - Sqrt[b^2 - 4 c])
But by evaluate it a second time several errors occurs:
Solution 1
General::ivar: 1/2 (-b-Sqrt[b^2-4 c]) is not a valid variable. >>
General::ivar: 1/2 (-b-Sqrt[b^2-4 c]) is not a valid variable. >>
ReplaceAll::reps: {1/2 b (-b-Sqrt[Plus[<<2>>]])+1/4 (-b-Power[<<2>>])^2+c==0} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing. >>
1/2 (-b - Sqrt[b^2 - 4 c]) /.
1/2 b (-b - Sqrt[b^2 - 4 c]) + 1/4 (-b - Sqrt[b^2 - 4 c])^2 + c == 0
"Solution 2"
...
It seems to me, that the ReplaceRepeated in the if condition work global although it is a Module environment. Can anybody help? How I solve this problem?
Evaluate your code the first time
In[1]:= values = {b -> 1, c -> 0};
Solutions := Solve[x^2 + b*x + c == 0, x]
x1 := x /. Solutions[[1]];
x2 := x /. Solutions[[2]];
"Solution 1"
x1
"Solution 2"
x2
"Choose ~preferred~ Solution, which is -1 when using values"
If[Module[{list = values}, ReplaceRepeated[x1 == -1, list]], x = x1, x = x2]
"~Preferred~ Solution"
x
Out[5]= "Solution 1"
Out[6]= 1/2 (-b - Sqrt[b^2 - 4 c])
Out[7]= "Solution 2"
Out[8]= 1/2 (-b + Sqrt[b^2 - 4 c])
Out[9]= "Choose ~preferred~ Solution, which is -1 when using values"
Out[10]= 1/2 (-b - Sqrt[b^2 - 4 c])
Out[11]= "~Preferred~ Solution"
Out[12]= 1/2 (-b - Sqrt[b^2 - 4 c])
All that is fine. What is the value of x now?
In[13]:= x
Out[13]= 1/2 (-b - Sqrt[b^2 - 4 c])
That is fine. Now begin to evaluate your code a second time.
In[14]:= values = {b -> 1, c -> 0};
Solutions := Solve[x^2 + b*x + c == 0, x]
Suppose you want to evaluate Solutions now. That is going to evaluate your quadratic in x, but you see x is no longer just a symbol with no value, it is going to use the value of x in Out[13] and Solutions is
In[15]:= Solutions
During evaluation of In[15]:= Solve::ivar: 1/2 (-b-Sqrt[b^2-4 c]) is not a valid variable. >>
Out[15]= Solve[1/2b(-b-Sqrt[b^2-4c])+1/4(-b-Sqrt[b^2-4c])^2+c==0, 1/2(-b-Sqrt[b^2-4c])]
And that is why it fails. You previously assigned x a value, you are using x and thus that value in your Solve. Perhaps you want to Clear your x before evaluating all this.
Related
I am trying to solve the following system of equation using sympy.
from sympy import *
n = 4
K = 2
a = symbols(f"a_:{int(n)}", real=True)
b = symbols(f"b_:{int(n)}", real=True)
X = symbols(f"X_:{int(K)}", real=True)
Y = symbols(f"Y_:{int(K)}", real=True)
lambda_ = symbols("lambda",real=True)
mu = symbols(f"mu_:{int(K)}", real=True)
list_eq = [
# (1)
Eq(a[0] + a[1] + a[2] + a[3], 0),
Eq(a[0] + a[1], X[0]),
Eq(a[2] + a[3], X[1]),
# (2)
Eq(b[0] + b[1] + b[2] + b[3], 0),
Eq(b[0] + b[1], Y[0]),
Eq(b[2] + b[3], Y[1]),
# (3)
Eq(b[0], a[0] - lambda_ - mu[0]),
Eq(b[1], a[1] - lambda_ - mu[0]),
Eq(b[2], a[2] - lambda_ - mu[1]),
Eq(b[3], a[3] - lambda_ - mu[1]),
]
solve(list_eq, dict=True)
[{X_0: -b_2 - b_3 + mu_0 - mu_1,
X_1: b_2 + b_3 - mu_0 + mu_1,
Y_0: -b_2 - b_3,
Y_1: b_2 + b_3,
a_0: -b_1 - b_2 - b_3 + mu_0/2 - mu_1/2,
a_1: b_1 + mu_0/2 - mu_1/2,
a_2: b_2 - mu_0/2 + mu_1/2,
a_3: b_3 - mu_0/2 + mu_1/2,
b_0: -b_1 - b_2 - b_3,
lambda: -mu_0/2 - mu_1/2}]
The analytical solution for b is
b_0 = a_0 + (1/2)*(Y_0 - X_0)
b_1 = a_1 + (1/2)*(Y_0 - X_0)
b_2 = a_2 + (1/2)*(Y_1 - X_1)
b_3 = a_3 + (1/2)*(Y_1 - X_1)
However sympy does not manage to simplify the results and is still using mu_0 and mu_1 in the solution.
Is it possible to simplify those variables in the solution ?
For more details, the system i'm trying to solve is an optimization problem under constraints:
min_b || a - b ||^2 such that b_0 + b_1 + b_2 + b_3 = 0 and b_0 + b_1 = Y_0 and b_2 + b_3 = Y_1.
We assume that a_0 + a_1 + a_2 + a_3 = 0 and a_0 + a_1 = X_0 and a_2 + a_3 = X_1.
Therefore, the equations (1) are the assumptions on a and the equations (2) and (3) are the KKT equations.
You can eliminate variables from a system of linear or polynomial equations using a Groebner basis:
In [61]: G = groebner(list_eq, [*mu, lambda_, *b, *a, *X, *Y])
In [62]: for eq in G: pprint(eq)
X₁ - Y₁ + 2⋅λ + 2⋅μ₀
-X₁ + Y₁ + 2⋅λ + 2⋅μ₁
X₁ + Y₁ + 2⋅a₁ + 2⋅b₀
-X₁ + Y₁ - 2⋅a₁ + 2⋅b₁
-X₁ - Y₁ + 2⋅a₃ + 2⋅b₂
X₁ - Y₁ - 2⋅a₃ + 2⋅b₃
X₁ + a₀ + a₁
-X₁ + a₂ + a₃
X₀ + X₁
Y₀ + Y₁
Here the first two equations have mu and lambda but the others have these symbols eliminated. You can use G[2:] to get the equations that do not involve mu and lambda. The order of the symbols in a lex Groebner basis determines which symbols are eliminated first from the equations. You can solve specifically for b in terms of a, X and Y by picking out the equations involving b:
In [63]: solve(G[2:6], b)
Out[63]:
⎧ X₁ Y₁ X₁ Y₁ X₁ Y₁ X₁ Y₁ ⎫
⎨b₀: - ── - ── - a₁, b₁: ── - ── + a₁, b₂: ── + ── - a₃, b₃: - ── + ── + a₃⎬
⎩ 2 2 2 2 2 2 2 2 ⎭
This is not exactly the form you suggested but the form of solution for the problem is not unique because of the constraints among the variables it is expressed in. There are many equivalent ways to express b in terms of a, X and Y even after eliminating mu and lambda because a, X and Y are not independent (they are 8 symbols connected by 4 constraints).
Sometimes adding auxiliary equations with the pattern you desire and indicating what you don't want as a solution variable can help you get closer to what you desired:
[38] eqs = list_eq + [Y[0]-X[0]-var('z0'), Y[1]-X[1]-var('z1')]
[39] sol = Dict(solve(eqs, exclude=a, dict=True)[0]); sol
I use parse_expr("-5 + 2*x + 3 - 7*x + 5 - 3*x", evaluate=False).
According to documentation for evaluate=False, I expected to keep the order of the expression:
"When False, the order of the arguments will remain as they were in the string ..."
But the result is sorted:
-7*x - 3*x + 2*x - 5 + 3 + 5
sympy=1.4
It is as advertised:
>>> u = parse_expr("-5 + 2*x + 3 - 7*x + 5 - 3*x", evaluate=False); u.args
(-5, 2*x, 3, -7*x, 5, -3*x)
The printer, however, prints them in sorted order. It seems like there should be an easier way to do the following, but it works:
>>> s=StrPrinter(dict(order='none'))
>>> s._print_Add(u)
-5 + 2*x + 3 - 7*x + 5 - 3*x
Objective function => x1 - 2x2
Subject to =>
x2 <= 5
x1 - x2 >= 2
x1 ,x2, x3 >= 0
Maximize?
convert to standard form :
Maximize -> -x1 + 2x2
Subject to ->
x2 <= 5
-x1 + x2 <= -2
convert to slack form :
Z = -x1 + 2x2
x3 = 5 - x2
x4 = -2 +x1 -x2
Basic solution (0,0,5,-2)
Can I found optimal solution in here? If not why?
If I have an expression like the following 2 * a + 2 * b + 1, is there a way to effectively factor out the 2 without substituting it for a symbol?
Edit: My own answer below does not seem to work for rational coefficients, e.g., collect(a / 2 + b / 2 + 1, Rational(1, 2)) returns a / 2 + b / 2 + 1.
I used collect_const.
a, b = symbols('a b')
test = 2 * a + 2 * b + 1
collect_const(test, 2)
int sum_down(int x)
{
if (x >= 0)
{
x = x - 1;
int y = x + sum_down(x);
return y + sum_down(x);
}
else
{
return 1;
}
}
What is this smallest integer value of the parameter x, so that the returned value is greater than 1.000.000 ?
Right now I am just doing it by trial and error and since this question is asked via a paper format. I don't think I will have enough time to do trial and error. Question is, how do you guys visualise this quickly such that it can be solved easily. Thanks guys and I am new to programming so thanks in advance!
The recursion logic:
x = x - 1;
int y = x + sum_down(x);
return y + sum_down(x);
can be simplified to:
x = x - 1;
int y = x + sum_down(x) + sum_down(x);
return y;
which can be simplified to:
int y = (x-1) + sum_down(x-1) + sum_down(x-1);
return y;
which can be simplified to:
return (x-1) + 2*sum_down(x-1);
Put in mathematical form,
f(N) = (N-1) + 2*f(N-1)
with the recursion terminating when N is -1. f(-1) = 1.
Hence,
f(0) = -1 + 2*1 = 1
f(1) = 0 + 2*1 = 2
f(2) = 1 + 2*2 = 5
...
f(18) = 17 + 2*f(17) = 524269
f(19) = 18 + 2*524269 = 1048556
Your program can be written this way (sorry about c#):
public static void Main()
{
int i = 0;
int j = 0;
do
{
i++;
j = sum_down(i);
Console.Out.WriteLine("j:" + j);
} while (j < 1000000);
Console.Out.WriteLine("i:" + i);
}
static int sum_down(int x)
{
if (x >= 0)
{
return x - 1 + 2 * sum_down(x - 1);
}
else
{
return 1;
}
}
So at first iteration you'll get 2, then 5, then 12... So you can neglect the x-1 part since it'll stay little compared to the multiplication.
So we have:
i = 1 => sum_down ~= 4 (real is 2)
i = 2 => sum_down ~= 8 (real is 5)
i = 3 => sum_down ~= 16 (real is 12)
i = 4 => sum_down ~= 32 (real is 27)
i = 5 => sum_down ~= 64 (real is 58)
So we can say that sum_down(x) ~= 2^x+1. Then it's just basic math with 2^x+1 < 1 000 000 which is 19.
A bit late, but it's not that hard to get an exact non-recursive formula.
Write it up mathematically, as explained in other answers already:
f(-1) = 1
f(x) = 2*f(x-1) + x-1
This is the same as
f(-1) = 1
f(x+1) = 2*f(x) + x
(just switched from x and x-1 to x+1 and x, difference 1 in both cases)
The first few x and f(x) are:
x: -1 0 1 2 3 4
f(x): 1 1 2 5 12 27
And while there are many arbitrary complicated ways to transform this into a non-recursive formula, with easy ones it often helps to write up what the difference is between each two elements:
x: -1 0 1 2 3 4
f(x): 1 1 2 5 12 27
0 1 3 7 15
So, for some x
f(x+1) - f(x) = 2^(x+1) - 1
f(x+2) - f(x) = (f(x+2) - f(x+1)) + (f(x+1) - f(x)) = 2^(x+2) + 2^(x+1) - 2
f(x+n) - f(x) = sum[0<=i<n](2^(x+1+i)) - n
With eg. a x=0 inserted, to make f(x+n) to f(n):
f(x+n) - f(x) = sum[0<=i<n](2^(x+1+i)) - n
f(0+n) - f(0) = sum[0<=i<n](2^(0+1+i)) - n
f(n) - 1 = sum[0<=i<n](2^(i+1)) - n
f(n) = sum[0<=i<n](2^(i+1)) - n + 1
f(n) = sum[0<i<=n](2^i) - n + 1
f(n) = (2^(n+1) - 2) - n + 1
f(n) = 2^(n+1) - n - 1
No recursion anymore.
How about this :
int x = 0;
while (sum_down(x) <= 1000000)
{
x++;
}
The loop increments x until the result of sum_down(x) is superior to 1.000.000.
Edit : The result would be 19.
While trying to understand and simplify the recursion logic behind the sum_down() function is enlightening and informative, this snippet tend to be logical and pragmatic in that it does not try and solve the problem in terms of context, but in terms of results.
Two lines of Python code to answer your question:
>>> from itertools import * # no code but needed for dropwhile() and count()
Define the recursive function (See R Sahu's answer)
>>> f = lambda x: 1 if x<0 else (x-1) + 2*f(x-1)
Then use the dropwhile() function to remove elements from the list [0, 1, 2, 3, ....] for which f(x)<=1000000, resulting in a list of integers for which f(x) > 1000000. Note: count() returns an infinite "list" of [0, 1, 2, ....]
The dropwhile() function returns a Python generator so we use next() to get the first value of the list:
>>> next(dropwhile(lambda x: f(x)<=1000000, count()))
19