Why don't I get a float result? - wxmaxima

c2: (x-0.5)^2+y^2=1;
solve(c2,y);
cs2: map(rhs, %);
at(cs2,[x=0.5]);
I expect to see [-1,1], but I get this instead
What should I do?
Incidentally, maxima cannot plot this equation for a reason unknown to me.
plot2d(cs2, [x,-2.5,2.5],[same_xy, true]);
plot2d: expression evaluates to non-numeric value everywhere in plotting range.
plot2d: expression evaluates to non-numeric value everywhere in plotting range.
plot2d: nothing to plot.
Build info:
wxbuild_info();
wxMaxima version: 19.07.0
using wxWidgets version: wxWidgets 3.0.4
Maxima version: 5.43.2
Maxima build date: 2020-02-21 05:22:38
Host type: x86_64-pc-linux-gnu
System type: BSD BSD NIL
Lisp implementation type: GNU Common Lisp (GCL)
Lisp implementation version: GCL 2.6.12
Whole output:

I can't reproduce the behavior you're seeing. I compiled Maxima 5.43.2 (version number slightly mixed up in build_info output below) and I don't get the results you're seeing. Here's what I see with the command line interface (I get the same result with wxMaxima).
(%i1) c2: (x - 0.5)^2 + y^2 = 1;
2 2
(%o1) y + (x - 0.5) = 1
(%i2) solve (c2, y);
rat: replaced -0.5 by -1/2 = -0.5
2 2
sqrt((- 4 x ) + 4 x + 3) sqrt((- 4 x ) + 4 x + 3)
(%o2) [y = - ------------------------, y = ------------------------]
2 2
(%i3) cs2: map (rhs, %);
2 2
sqrt((- 4 x ) + 4 x + 3) sqrt((- 4 x ) + 4 x + 3)
(%o3) [- ------------------------, ------------------------]
2 2
(%i4) at (cs2, x = 0.5);
(%o4) [- 1.0, 1.0]
(%i5) plot2d(cs2, [x,-2.5,2.5],[same_xy, true]);
plot2d: expression evaluates to non-numeric value somewhere in plotting range.
plot2d: expression evaluates to non-numeric value somewhere in plotting range.
(%o5) [/tmp/maxout9196.gnuplot, /tmp/maxplot.x11]
The plot2d displays a circle.
For the record, build_info reports:
Maxima version: "5.43.1_10_g5476356eb"
Maxima build date: "2022-01-31 12:13:20"
Host type: "i686-pc-linux-gnu"
Lisp implementation type: "CLISP"
Lisp implementation version: "2.49 (2010-07-07) (built 3605610186) (memory 3852648802)"
User dir: "/home/robert/.maxima"
Temp dir: "/tmp"
Object dir: "/home/robert/tmp/maxima-read-only-git/maxima-code/binary/5_43_1_10_g5476356eb/clisp/2_49__2010_07_07___built_3605610186___memory_3852648802_"
Frontend: false
It's puzzling that you are seeing a different result for solve. Do you get the same result in command line Maxima, or something else?

Related

simplifying composite function (diff) in maxima (chain rule for differentiation)

How can the following formula be simplified in Maxima:
diff(h((x-1)^2),x,1)
Mathematically it should be : 2*(x-1)*h'((x-1)^2)
But maxima gives : d/dx h((x-1)^2)
Maxima doesn't apply the chain rule by default, but there is an add-on package named pdiff (which is bundled with the Maxima installation) which can handle it.
pdiff means "positional derivative" and it uses a different, more precise, notation to indicate derivatives. I'll try it on the expression you gave.
(%i1) load ("pdiff") $
(%i2) diff (h((x - 1)^2), x);
2
(%o2) 2 h ((x - 1) ) (x - 1)
(1)
The subscript (1) indicates a first derivative with respect to the argument of h. You can convert the positional derivative to the notation which Maxima usually uses.
(%i3) convert_to_diff (%);
!
d !
(%o3) 2 (x - 1) (----- (h(g485))! )
dg485 ! 2
!g485 = (x - 1)
The made-up variable name g485 is just a place-holder; the name of the variable could be anything (and if you run this again, chances are you'll get a different variable name).
At this point you can substitute for h or x to get some specific values. Note that ev(something, nouns) means to call any quoted (evaluation postponed) functions in something; in this case, the quoted function is diff.
(%i4) ev (%, h(u) := sin(u));
!
d !
(%o4) 2 (x - 1) (----- (sin(g485))! )
dg485 ! 2
!g485 = (x - 1)
(%i5) ev (%, nouns);
2
(%o5) 2 cos((x - 1) ) (x - 1)

minimum-difference constrained sparse least squares problem (called from python)

I'm struggling a bit finding a fast algorithm that's suitable.
I just want to minimize:
norm2(x-s)
st
G.x <= h
x >= 0
sum(x) = R
G is sparse and contains only 1s (and zeros obviously).
In the case of iterative algorithms, it would be nice to get the interim solutions to show to the user.
The context is that s is a vector of current results, and the user is saying "well the sum of these few entries (entries indicated by a few 1.0's in a row in G) should be less than this value (a row in h). So we have to remove quantities from the entries the user specified (indicated by 1.0 entries in G) in a least-squares optimal way, but since we have a global constraint on the total (R) the values removed need to be allocated in a least-squares optimal way amongst the other entries. The entries can't go negative.
All the algorithms I'm looking at are much more general, and as a result are much more complex. Also, they seem quite slow. I don't see this as a complex problem, although mixes of equality and inequality constraints always seem to make things more complex.
This has to be called from Python, so I'm looking at Python libraries like qpsolvers and scipy.optimize. But I suppose Java or C++ libraries could be used and called from Python, which might be good since multithreading is better in Java and C++.
Any thoughts on what library/package/approach to use to best solve this problem?
The size of the problem is about 150,000 rows in s, and a few dozen rows in G.
Thanks!
Your problem is a linear least squares:
minimize_x norm2(x-s)
such that G x <= h
x >= 0
1^T x = R
Thus it fits the bill of the solve_ls function in qpsolvers.
Here is an instance of how I imagine your problem matrices would look like, given what you specified. Since it is sparse we should use SciPy CSC matrices, and regular NumPy arrays for vectors:
import numpy as np
import scipy.sparse as spa
n = 150_000
# minimize 1/2 || x - s ||^2
R = spa.eye(n, format="csc")
s = np.array(range(n), dtype=float)
# such that G * x <= h
G = spa.diags(
diagonals=[
[1.0 if i % 2 == 0 else 0.0 for i in range(n)],
[1.0 if i % 3 == 0 else 0.0 for i in range(n - 1)],
[1.0 if i % 5 == 0 else 0.0 for i in range(n - 1)],
],
offsets=[0, 1, -1],
)
a_dozen_rows = np.linspace(0, n - 1, 12, dtype=int)
G = G[a_dozen_rows]
h = np.ones(12)
# such that sum(x) == 42
A = spa.csc_matrix(np.ones((1, n)))
b = np.array([42.0]).reshape((1,))
# such that x >= 0
lb = np.zeros(n)
Next, we can solve this problem with:
from qpsolvers import solve_ls
x = solve_ls(R, s, G, h, A, b, lb, solver="osqp", verbose=True)
Here I picked CVXOPT but there are other open-source solvers you can install such as ProxQP, OSQP or SCS. You can install a set of open-source solvers by: pip install qpsolvers[open_source_solvers]. After some solvers are installed, you can list those for sparse matrices by:
print(qpsolvers.sparse_solvers)
Finally, here is some code to check that the solution returned by the solver satisfies our constraints:
tol = 1e-6 # tolerance for checks
print(f"- Objective: {0.5 * (x - s).dot(x - s):.1f}")
print(f"- G * x <= h: {(G.dot(x) <= h + tol).all()}")
print(f"- x >= 0: {(x + tol >= 0.0).all()}")
print(f"- sum(x) = {x.sum():.1f}")
I just tried it with OSQP (adding the eps_rel=1e-5 keyword argument when calling solve_ls, otherwise the returned solution would be less accurate than the tol = 1e-6 tolerance) and it found a solution is 737 milliseconds on my (rather old) CPU with:
- Objective: 562494373088866.8
- G * x <= h: True
- x >= 0: True
- sum(x) = 42.0
Hoping this helps. Happy solving!

Exponential moving average in J

I currently am going through some examples of J, and am trying to do an exponential moving average.
For the simple moving average I have done as follows:
sma =: +/%[
With the following given:
5 sma 1 2 3 4 5
1.2 1.4 1.6 1.8 2
After some more digging I found an example of the exponential moving average in q.
.q.ema:{first[y]("f"$1-x)\x*y}
I have tried porting this to J with the following code:
ema =: ({. y (1 - x)/x*y)
However this results in the following error:
domain error
| ema=:({.y(1-x) /x*y)
This is with x = 20, and y an array of 20 random numbers.
A couple of things that I notice that might help you out.
1) When you declare a verb explicitly you need to use the : Explicit conjunction and in this case since you have a dyadic verb the correct form would be 4 : 'x contents of verb y' Your first definition of sma =: +/%[ is tacit, since no x or y variables are shown.
ema =: 4 : '({. y (1 - x)/x*y)'
2) I don't know q, but in J it looks as if you are trying to Insert / a noun 1 - x into a list of integers x * y. I am guessing that you really want to Divides %. You can use a gerunds as arguments to Insert but they are special nouns representing verbs and 1 - x does not represent a verb.
ema =: 4 : '({. y (1 - x)%x*y)'
3) The next issue is that you would have created a list of numbers with (1 - x) % x * y, but at that point y is a number adjacent to a list of numbers with no verb between which will be an error. Perhaps you meant to use y * (1 - x)%x*y ?
At this point I am not sure what you want exponential moving average to do and hope the clues I have provided will give you the boost that you need.

When does floating-point rounding-errors occur? [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 7 years ago.
As I was debugging my VBA code, I came across this weird phenomenon:
This loop
Dim x,y as Double
x = 0.7
y = 0.1
For x = x - y To x + y Step y
Next x
runs only twice!
I tried many variations of this code to nail down the problem, and here is what I came up with:
Replacing the loop boundaries with simple numbers (0.6 to 0.8) - helped.
Replacing variables with numbers (all the combinations) - didn't help.
Replacing the for-loop with do while/until loops - helped.
Replacing the values of x and y (y=0.01, 0.3, 0.4, 0.5, 0.7, 0.8, 0.9 - helped. 0.2, 0.6 -didn't help. x=1, 2 ,3 helped. x=4, 5, 6, 7, 8, 9 - didn't help.
Converting the Double to Decimal with CDec() - helped.
Using the Currency data type instead of Double - helped.
So what we have here is a floating-point rounding-error that happens on mysterious conditions.
What I'm trying to find out is what are those conditions, so we can avoid them.
Who will unveil this mystery?
(Pardon my English, it's not my mother tongue).
GD Falcon,
Generally in solving a For...Next loop it would not be advisable to use 'double' or 'decimal' or 'currency' variables as they provide a level of uncertainty in their accuracy, it's this level of inaccuracy that is wrecking havoc on your code as the actual stop parameter (when x-y, plus (n x y) = x+y) is, in terms of absolutes, an insolvable equation unless you limit the number of decimals it uses.
It is generally considered better practice to use integers (or long) variables in a For...Next loop as their outcome is more certain.
See also below post:
How to make For loop work with non integers
If you want it to run succesfully and iterate 3 times (as I expect you want)
Try like below:
Dim x, y As Double
x = 0.7
y = 0.1
For x = Round(x - y, 1) To Round(x + y, 1) Step Round(y, 1)
Debug.Print x
Next x
Again, it is better not to use Doubles in this particular way to begin with but if you must you would have to limit the number of decimals they calculate with or set a more vague end point (i.e. x > y, rather than x = y)
The coding you use implies that you wish to test some value x against a tolerance level of y.
Assuming this is correct it would imply testing 3 times where;
test_1: x = x - y
test_2: x = x
test_3: x = x + y
The below code would do the same but it would have a better defined scope.
Dim i As Integer
Dim x, y, w As Double
x = 0.7
y = 0.1
For i = -1 To 1 Step 1
w = x + (i * y)
Debug.Print w
Next i
Good luck !

Incorrect result of sum int-casted BitVec using Z3, Z3py

I am using the following python code to find two binary numbers that:
sum to a certain number
their highest bits cast to integers must sum up to 2
The second constraint is more important to me; and in my case, it will scale: let's say it might become that highest bits of [N] number must sum up to [M].
I am not sure why z3 does not give the correct result. Any hints? Thanks a lot.
def BV2Int(var):
return ArithRef(Z3_mk_bv2int(ctx.ref(), var.as_ast(), 0), var.ctx)
def main():
s = Solver()
s.set(':models', True)
s.set(':auto-cfgig', False)
s.set(':smt.bv.enable_int2bv',True)
x = BitVec('x',4)
y = BitVec('y',4)
s = Solver()
s.add(x+y == 16, Extract(3,3,x) + Extract(3,3,y) == 2)
s.check()
print s.model()
# result: [y = 0, x = 0], fail both constraint
s = Solver()
s.add(x+y == 16, BV2Int(Extract(3,3,x)) + BV2Int(Extract(3,3,y)) == 2)
s.check()
print s.model()
# result: [y = 15, x = 1], fail the second constraint
Update: Thanks the answer from Christoph. Here is a quick fix:
Extract(3,3,x) -> ZeroExt(SZ, Extract(3,3,x)) where SZ is the bit width of RHS minus 1.
(Aside: auto-cfgig should be auto-config.)
Note that bv2int and int2bv are essentially treated as uninterpreted, so if this part is crucial to your problem, then don't use them (see documentation and previous questions).
The problem with this example are the widths of the bit-vectors. Both x and y are 4-bit variables, and the numeral 16 as a 4-bit vector is 0 (modulo 2^4), so, indeed x + y is equal to 16 when x=0 and y=0.
Further, the Extract(...) terms extract 1-bit vectors, which means that the sum Ex.. + Ex.. is again a 1-bit value and the numeral 2 as a 1-bit vector is 0 (modulo 2^1), i.e., it is indeed the case that Ex... + Ex... = 2.