How to access specific elements in an array in maxima? - maxima

After using the solve command to solve two simultaneous non linear equations, I am getting an array of x and y and I need to access specific elements in this array.
A: 0.500000000000000$
B: 0.709506070053745$
C: 0.242527534593605$
D: 0.719012140107490$
E: 0.357164044380080$
F:-0.505315948652670$
G: 0.181895650945204$
H: 0.300000000000000$
solve([
x^2*(A*y^3+B*y-C)-D*x*y^2+E*y^3,
A*x^2+(x/y^2)*(H*y+G)+F
] ,[x,y]),numer;
Here, x and y contain 8 values each and I need to access say only the 2nd element.

Maxima returns a list of results here (a maxima array is something slightly different). Each element of the list is a pair of equations (x = ... and y = ...). For others reading this, the results look like
[[x = .06111426947129051, y = .1679154401926679],
[x = - 6.026109660574413, y = .3056091599125177],
[x = .2909171173159695, y = .4452108480953128],
[x = .4561445354339108 %i + 1.180400961416986,
y = .8695950265919334 %i + .05136082885038127],
[x = 1.180400961416985 - .4561445354339104 %i,
y = .05136082885038127 - .8695950265919334 %i],
[x = .06097600174281474 %i - 0.77772869099467,
y = 0.792517152411182 %i - .5107285531053073],
[x = - .06097600174281463 %i - 0.77772869099467,
y = - 0.792517152411182 %i - .5107285531053073],
[x = 0, y = 0]]
Now, I'm not sure from your question whether you want just each y coordinate, or whether you want the second solution that solve found. For the second solution, just use [n] to get the n'th thing. So if I stored the list above as the variable solns, I could use
(%i12) solns[2];
(%o12) [x = - 6.026109660574413, y = .3056091599125177]
If you want each y coordinate, you have to map into the list. For example, try this:
(%i14) map(lambda([pair], rhs(second(pair))), solns);
(%o14) [.1679154401926679,
.3056091599125177,
.4452108480953128,
.8695950265919334 %i + .05136082885038127,
.05136082885038127 - .8695950265919334 %i,
0.792517152411182 %i - .5107285531053073,
- 0.792517152411182 %i - .5107285531053073,
0]
(I tidied up the formatting of the output slightly). Or you could equally do
map(rhs, map(second, solns));
which gives exactly the same answer but without needing to write a lambda form.

Related

I don't Understand "How Lua save data on the same variable when we Iterate over it"

I know Lua remember value in the same field/function with the Same defined Variable. but I still lack the concept behind it. Let's say I'see Int Variable = 2 which can be modify if we iterate over it Int variable = 8
Same logic I was applying on the Code. I got the results, but I didn't understand the concept behind it.
You Can see in my Code I was saving some value in Var x and saveX
and I was doing saveX = x from my logic The value of x should be saved inside saveX instead it was saving the loop value as I'm applying over it. Why is that?
-- Graphical Representation of table1
--[[ { { {},{},{},{} },
{ {},{},{},{} },
{ {},{},{},{} },
{ {},{},{},{} } } ]]
_Gtable1 = {}
for y = 1, 4 do
table.insert(_Gtable1, {})
for x = 1, 4 do
table.insert(_Gtable1[y], {
x = (x - 1) * 10, --Coordinate value of X
y = (y - 1) * 10, --Coordinate value of Y
-- what if i want to save Coordinate value on another variable How should i do?
saveX = x, -- Saving Loop X
saveY = y, -- Saving Loo Y
t = "Check" -- to Debug
})
end
end
ti = _Gtable1
for y = 1, 4 do
for x = 1, 4 do
tim = ti[y][x]
-- print(tim.saveX) -- output 1, 2, 3, 4
print(tim.x) -- output 0, 10, 20, 30
end
end
I hope I understood the question:
Let's simplify the example:
local t = {
x = 10,
y = x,
}
You assume t.y is 10, because you declared it a line before that? But it is nil here, because x = 10, is no variable. It's part of the table constructor and can not be referenced in the same constructor. Check out https://www.lua.org/pil/3.6.html for more details.
After the constructor has finished, you can access that as t.x (not x!).
Now for your example, you need to move (x - 1) * 10 outside the constructor, e.g.: local tempX = (x - 1) * 10. Then use tempX inside the constructor. Or you can set your values individually, e.g. _Gtable1[y][x].saveX = _Gtable1[y][x].x. I would prefer the former.

Max and Min of a set of variables in z3py

I have a problem where I want to limit the range of a real variable between the maximum and minimum value of another set of real variables.
s = Solver()
y = Real('y')
Z = RealVector('z', 10)
s.add(And(y >= min(Z), y <= max(Z)))
Is there a way to do this in z3py?
You can use Axel's solution; though that one requires you to create an extra variable and also asserts more constraints than needed. Moreover, it doesn't let you use min and max as simple functions. It might be easier to just program this in a functional way, like this:
# Return minimum of a vector; error if empty
def min(vs):
m = vs[0]
for v in vs[1:]:
m = If(v < m, v, m)
return m
# Return maximum of a vector; error if empty
def max(vs):
m = vs[0]
for v in vs[1:]:
m = If(v > m, v, m)
return m
Another difference is that in the functional style we throw an error if the vector is empty. In the other style, the result will essentially be unconstrained. (i.e., min/max can take any value.) You should consider which semantics is right for your application, in case the vector you're passing might be empty. (At the least, you should change it so it prints out a nicer error message. Currently it'll throw an IndexError: list index out of range error if given an empty vector.)
Now you can say:
s = Solver()
y = Real('y')
Z = RealVector('z', 10)
s.add(And(y >= min(Z), y <= max(Z)))
print (s.check())
print (s.model())
This prints:
sat
[z__7 = -1,
z__0 = -7/2,
z__4 = -5/2,
z__5 = -2,
z__3 = -9/2,
z__2 = -4,
z__8 = -1/2,
y = 0,
z__9 = 0,
z__6 = -3/2,
z__1 = -3]
You could benefit from Hakan Kjellerstrand's collection of useful z3py definitions:
from z3 import *
# Functions written by Hakan Kjellerstrand
# http://hakank.org/z3/
# The following can be used by importing http://www.hakank.org/z3/z3_utils_hakank.py
# v is the maximum value of x
def maximum(sol, v, x):
sol.add(Or([v == x[i] for i in range(len(x))])) # v is an element in x)
for i in range(len(x)):
sol.add(v >= x[i]) # and it's the greatest
# v is the minimum value of x
def minimum(sol, v, x):
sol.add(Or([v == x[i] for i in range(len(x))])) # v is an element in x)
for i in range(len(x)):
sol.add(v <= x[i]) # and it's the smallest
s = Solver()
y = Real('y')
zMin = Real('zMin')
zMax = Real('zMax')
Z = RealVector('z', 10)
maximum(s, zMin, Z)
minimum(s, zMax, Z)
s.add(And(y >= zMin, y <= zMax))
print(s.check())
print(s.model())

Create a path in a grid in prolog

I have to create a path between two given points in a grid in Prolog. The code I have so far is:
createPath(GridSize, BeginPosition, EndPosition, VisitedPoints, Path):-
nextStep(BeginPosition, NextStep, GridSize),
(
NextStep \== EndPosition,
->
nonmember(NextStep, VisitedPoints),
add(NextStep, VisitedPoints, NewVisitedPoints),
add(NextStep, Path, NewPath),
createPath(GridSize, NextStep, EndPosition, NewVisitedPoints, NewPath)
;
???
).
A little bit of explanation of my code:
GridSize is just an integer. If it is 2, the grid is a 2x2 grid. So all the grids are square.
The BeginPosition and EndPosition are shown like this: pos(X,Y).
The function nextStep looks for a valid neigbor of a given position. The values of X and Y have to be between 1 and the grid size. I've declared 4 different predicates of nextStep: X + 1, X - 1, Y + 1 and Y - 1.
This is the code:
nextStep(pos(X,Y),pos(X1,Y),GridSize):-
X1 is X + 1,
X1 =< GridSize.
nextStep(pos(X,Y),pos(X1,Y),_):-
X1 is X - 1,
X1 >= 1.
nextStep(pos(X,Y),pos(X,Y1),GridSize):-
Y1 is Y + 1,
Y1 =< GridSize.
nextStep(pos(X,Y),pos(X,Y1),_):-
Y1 is Y - 1,
Y1 >= 1.
nonmember returns true if a given element doesn't occur in a given list.
add adds an element to a given list, and returns the list with that element in it.
Another thing to know about VisitedPoints: Initially the BeginPosition and EndPosition are stored in that list. For example, if I want to find a path in a 2x2 grid, and I have to avoid point pos(2,1), then I will call the function like this:
createPath(2, pos(1,1), pos(2,2), [pos(1,1),pos(2,2),pos(2,1)], X).
The result I should get of it, should be:
X = [pos(1,2)]
Because that is the point needed to connect pos(1,1) and pos(2,2).
My question is, how can I stop the code from running when NextStep == EndPosition. In other words, what do I have to type at the location of the '???' ? Or am I handling this problem the wrong way?
I'm pretty new to Prolog, and making the step from object oriented languages to this is pretty hard.
I hope somebody can answer my question.
Kind regards,
Walle
I think you just placed the 'assignment' to path at the wrong place
createPath(GridSize, BeginPosition, EndPosition, VisitedPoints, Path):-
nextStep(BeginPosition, NextStep, GridSize),
(
NextStep \== EndPosition,
->
nonmember(NextStep, VisitedPoints),
add(NextStep, VisitedPoints, NewVisitedPoints),
% add(NextStep, Path, NewPath),
% createPath(GridSize, NextStep, EndPosition, NewVisitedPoints, NewPath)
createPath(GridSize, NextStep, EndPosition, NewVisitedPoints, Path)
;
% ???
% bind on success the output variable, maybe add EndPosition
Path = VisitedPoints
).
Maybe this is not entirely worth an answer, but a comment would be a bit 'blurry'

Understanding the indexing of bound variables in Z3

I am trying to understand how the bound variables are indexed in z3.
Here in a snippet in z3py and the corresponding output. ( http://rise4fun.com/Z3Py/plVw1 )
x, y = Ints('x y')
f1 = ForAll(x, And(x == 0, Exists(y, x == y)))
f2 = ForAll(x, Exists(y, And(x == 0, x == y)))
print f1.body()
print f2.body()
Output:
ν0 = 0 ∧ (∃y : ν1 = y)
y : ν1 = 0 ∧ ν1 = y
In f1, why is the same bound variable x has different index.(0 and 1). If I modify the f1 and bring out the Exists, then x has the same index(0).
Reason I want to understand the indexing mechanism:
I have a FOL formula represented in a DSL in scala that I want to send to z3. Now ScalaZ3 has a mkBound api for creating bound variables that takes index and sort as arguments. I am not sure what value should I pass to the index argument. So, I would like to know the following:
If I have two formulas phi1 and phi2 with maximum bound variable indexes n1 and n2, what would be the index of x in ForAll(x, And(phi1, phi2))
Also, is there a way to show all the variables in an indexed form? f1.body() just shows me x in indexed form and not y. (I think the reason is that y is still bound in f1.body())
Z3 encodes bound variables using de Bruijn indices.
The following wikipedia article describes de Bruijn indices in detail:
http://en.wikipedia.org/wiki/De_Bruijn_index
Remark: in the article above the indices start at 1, in Z3, they start at 0.
Regarding your second question, you can change the Z3 pretty printer.
The Z3 distribution contains the source code of the Python API. The pretty printer is implemented in the file python\z3printer.py.
You just need to replace the method:
def pp_var(self, a, d, xs):
idx = z3.get_var_index(a)
sz = len(xs)
if idx >= sz:
return seq1('Var', (to_format(idx),))
else:
return to_format(xs[sz - idx - 1])
with
def pp_var(self, a, d, xs):
idx = z3.get_var_index(a)
return seq1('Var', (to_format(idx),))
If you want to redefine the HTML pretty printer, you should also replace.
def pp_var(self, a, d, xs):
idx = z3.get_var_index(a)
sz = len(xs)
if idx >= sz:
# 957 is the greek letter nu
return to_format('ν<sub>%s</sub>' % idx, 1)
else:
return to_format(xs[sz - idx - 1])
with
def pp_var(self, a, d, xs):
idx = z3.get_var_index(a)
return to_format('ν<sub>%s</sub>' % idx, 1)

How to assign the output of solve in maxima to a variable?

I am using xmaxima to solve two simultaneous non-linear equations using the 'solve' command.The answer displayed is x=[ans1, ans2,..], y=[ans1,ans2,...], But it is'int getting stored onto the variable 'x' and 'y' .
How do I assign the output to a variable so that I can use the output for further calculations.
The xmaxima code is as below:
A:0.500000000000000$
B:0.709506070053745$
C:0.242527534593605$
D:0.719012140107490$
E: 0.357164044380080$
F:-0.505315948652670$
G:0.181895650945204$
H: 0.300000000000000$
[x,y]=solve([x^2*(A*y^3+B*y-C)-D*x*y^2+E*y^3,A*x^2+(x/y^2)*(H*y+G)+F],[x,y]),numer;
output is:
[x, y] = [[x = 0.0611142802814223, y = 0.167915465898175],
[x = - 6.026109660574413, y = 0.305609155632444],
[x = 0.290917101108745, y = 0.445210848095313],
[x = 0.456144541234576 %i + 1.180400965797426,
y = 0.869595022612534 %i + 0.051360830266336],
[x = 1.180400965797425 - 0.456144541234575 %i,
y = 0.051360830266336 - 0.869595022612534 %i],
[x = 0.0609759975012744 %i - 0.777728688525087,
y = 0.792517145089706 %i - 0.51072855430292],
[x = - 0.0609759975012744 %i - 0.777728688525087,
y = - 0.792517145089706 %i - 0.51072855430292],
[x = 0, y = 0]]
Firstly, note that there is more than one solution, so you have to decide what you want to do with them. One option is the following:
(%i9) solutions: solve([x^2*(A*y^3+B*y-C)-D*x*y^2+E*y^3,A*x^2+(x/y^2)*(H*y+G)+F],[x,y]), numer$
<snipped some info lines from rat>
(%i10) xvals: map(rhs, map(first, solutions));
(%o10) [.06111426947129051, - 6.026109660574413, .2909171173159695,
.4561445354339108 %i + 1.180400961416986,
1.180400961416985 - .4561445354339104 %i,
.06097600174281474 %i - 0.77772869099467,
- .06097600174281463 %i - 0.77772869099467, 0]
(%i11) yvals: map(rhs, map(second, solutions));
(%o11) [.1679154401926679, .3056091599125177, .4452108480953128,
.8695950265919334 %i + .05136082885038127,
.05136082885038127 - .8695950265919334 %i,
0.792517152411182 %i - .5107285531053073,
- 0.792517152411182 %i - .5107285531053073, 0]
Then you can get hold of the x,y pair for a solution via xvals[k] and yvals[k] (where you choose k between 1 and 8).

Resources