Maxima - differentiating a piecewise function - maxima

Suppose you have a function defined by intervals, such as
f(x):=block(if x<0 then x^2 else x^3);
When we differentiate it with
diff(f(x),x);
we get
d/dx (if x<0 then x^2 else x^3)
whereas I'd like to get
(if x<0 then 2*x else 3*x^2)
Is there a way to obtain such result?

This may help in a simple case:
(%i1) f(x):= charfun(x<0)*x^2 + charfun(x>=0)*x^3$
(%i2) gradef(charfun(y), 0)$
(%i3) diff(f(x),x);
2
(%o3) 2 x charfun(x < 0) + 3 x charfun(x >= 0)
charfun, gradef
You can try also Pw.mac package from Richard Hennessy.

Here's a different approach using a simplification rule for "if" expressions. The unsolved part here is to detect discontinuities and generate delta functions for those locations. If you want to ignore those, you can define FOO to return 0. Note that I didn't attempt to implement the function discontinuities; that part is unsolved here. I can give it a try if there is interest.
(%i1) display2d : false $
(%i2) matchdeclare ([aa, bb, cc], all, xx, symbolp) $
(%i3) 'diff (if aa then bb else cc, xx) $
(%i4) tellsimpafter (''%, apply ("if", [aa, diff (bb, xx), true, diff (cc, xx)]) + FOO (aa, bb, cc, xx)) $
(%i5) FOO (a, b, c, x) := 'lsum ((ev (c, x = d) - ev (b, x = d)) * delta (d, x), d, discontinuities (a, x)) $
(%i6) diff (if x > 0 then x^2 else x^3, x);
(%o6) (if x > 0 then 2*x else 3*x^2)+'lsum((d^3-d^2)*delta(d,x),d,
discontinuities(x > 0,x))

Building on slitinov's answer I wrote this quite naive implementation for functions with more than two "pieces":
gradef(charfun(dummy),0)$
/* piecewise function definition */
itv: [[x<0],[x>=0,x<1], [x>=1]]; /* intervals */
fi: [ 1, x^2+1, 2*x ]; /* local functions */
/* creation of global function f and its derivative df */
f:0;
for i: 1 thru 3 do f:f+charfun(apply("and",itv[i]))*fi[i];
df:diff(f,x);
/* display of local functions and derivatives */
for i: 1 thru 3 do (
apply(assume,itv[i]),
newline(),
print(itv[i]),
print("f = ",ev(f)),
print("df = ",ev(df)),
apply(forget,itv[i])
);
plot2d([f,df],[x,-2,3],[y,-1,5],[style,[lines,4,3],[lines,2,2]]);

Related

add iteratively in z3

I want to check the value of a, b, c, and if value 'a' equals to 1, 'x' is added one. We continue the process for values 'b' and 'c'.
So if a=1, b=1, c=1, the result of x should be 3.
if a=1, b=1, c=0, so the result of x should be 2.
Any methods to be implemented in z3?
The source code looks like this:
from z3 import *
a, b, c = Ints('a b c')
x, y = Ints('x y')
s = Solver()
s.add(If(a==1, x=x + 1, y = y-1))
s.add(If(b==1, x=x + 1, y = y-1))
s.add(If(c==1, x=x + 1, y = y-1))
s.check()
print s.model()
Any suggestions about what I can do?
This sort of "iterative" processing is usually modeled by unrolling the assignments and creating what's known as SSA form. (Static single assignment.) In this format, every variable is assigned precisely once, but can be used many times. This is usually done by some underlying tool as it is rather tedious, but you can do it by hand as well. Applied to your problem, it'd look something like:
from z3 import *
s = Solver()
a, b, c = Ints('a b c')
x0, x1, x2, x3 = Ints('x0 x1 x2 x3')
s.add(x0 == 0)
s.add(x1 == If(a == 1, x0+1, x0))
s.add(x2 == If(b == 1, x1+1, x1))
s.add(x3 == If(c == 1, x2+1, x2))
# Following asserts are not part of your problem, but
# they make the output interesting
s.add(b == 1)
s.add(c == 0)
# Find the model
if s.check() == sat:
m = s.model()
print("a=%d, b=%d, c=%d, x=%d" % (m[a].as_long(), m[b].as_long(), m[c].as_long(), m[x3].as_long()))
else:
print "no solution"
SSA transformation is applied to the variable x, creating as many instances as necessary to model the assignments. When run, this program produces:
a=0, b=1, c=0, x=1
Hope that helps!
Note that z3 has many functions. One you could use here is Sum() for the sum of a list. Inside the list you can put simple variables, but also expression. Here an example for both a simple and a more complex sum:
from z3 import *
a, b, c = Ints('a b c')
x, y = Ints('x y')
s = Solver()
s.add(a==1, b==0, c==1)
s.add(x==Sum([a,b,c]))
s.add(y==Sum([If(a==1,-1,0),If(b==1,-1,0),If(c==1,-1,0)]))
if s.check() == sat:
print ("solution:", s.model())
else:
print ("no solution possible")
Result:
solution: [y = 2, x = 2, c = 1, b = 0, a = 1]
If your problem is more complex, using BitVecs instead of Ints can make it run a little faster.
edit: Instead of Sum() you could also simply use addition as in
s.add(x==a+b+c)
s.add(y==If(a==1,-1,0)+If(b==1,-1,0)+If(c==1,-1,0))
Sum() makes sense towards readability when you have a longer list of variables, or when the variables already are in a list.

Maxima: How to replace the variables to simplify the equation?

(%i1) r: sqrt(x^2+y^2+z^2);
(r) sqrt(z^2+y^2+x^2)
(%i2) dx: diff(r,x);
(dx) x/sqrt(z^2+y^2+x^2)
I just show a simple code because my code is long and complex.
I want to simplify dx and get the result is x/r not x/sqrt(z^2+y^2+x^2).
However, I can't find the useful command.
Could somebody help me to solve this problem?
In this specific case, you can use subst, although ratsubst is probably useful in a greater number of cases.
(%i1) linel:65;
(%o1) 65
(%i2) r: sqrt(x^2+y^2+z^2);
2 2 2
(%o2) sqrt(z + y + x )
(%i3) diff (r, x);
x
(%o3) ------------------
2 2 2
sqrt(z + y + x )
(%i5) subst (r = 'r, %o3);
x
(%o5) -
r
(%i6) ratsubst ('r, r, %o3);
x
(%o6) -
r
Note that the single quote mark prevents evaluation, so that 'r is the symbol r instead of the value of r (namely sqrt(x^2 + y^2 + z^2)).

Substitute variable?

I'm trying to substitute L with Lα:
f(x) := c * (x + L);
c: L;
f(x), L: Lα;
I expected the output:
Lα * (x + Lα)
instead I got
L * (x + Lα)
Maybe I should define f(x) instead?
kill(all);
define(
f(x),
c * (x + L)
);
c: L;
f(x), L: Lα;
Nope — same result.
Do I substitute L for Lα in a wrong way?
Edit:
Turns out it is expected behaviour, as maxima evavluates expression only once. One can impose "infinite evaluation" via the flag infeval:
f(x), L: La, infeval;
=> La*(x + La)
Another solution is to use subst instead:
subst(
Lα, L, f(x)
);
(source)
You need to add an extra eval step to make this work:
f(x) := c * (x + L);
c: L;
f(x), L: Lα, eval;
Output:
Lα (x + Lα)
Use subst instead of ev.
(%i1) f(x) := c * (x + L)$
(%i2) c: L$
(%i3) subst(L=La,f(x));
(%o3) La (x + La)
But keep in mind that the function continues to be c*(x+L). The symbol c has been bound to L and if you then bind the symbol L to La, c will continue to be bound to L and not to La. Maxima variables work as in Lisp, which might be different to what you are used to in other languages.

Symbolic evaluation of expressions containing relational operators, possibly using Maxima

I'm looking for either another tool that will do symbolic evaluation of relational expressions, or perhaps a Maxima package that extends Maxima to enable such a feature.
As is, Maxima does not do this.
As far as I know maxima can work with relational operators in the manual:
http://maxima.sourceforge.net/docs/manual/maxima_7.html#SEC39
(%i1) [x, y, z] : [123, 456, 789];
(%o1) [123, 456, 789]
(%i2) is (x < y);
(%o2) true
(%i3) maybe (y > z);
(%o3) false
(%i4) if x >= z then 1 else 0;
(%o4) 0
(%i5) block ([S], S : 0, for i:1 while i <= 100 do S : S + i,
return (S));
(%o5) 5050
or even solve inequalities:
(%i4) load(fourier_elim)$
(%i5) fourier_elim([(x+1)*(x+2)>0],[x]);
(%o5) [- 1 < x] or [x < - 2]

Maxima: How to factor a expression in an expected form

I have an expression:
(b+2*ab+a+1)/c
I want to use Maxima to factor the equation treating (b+1) as a factor.
i.e. I want the expression in the following form:
[(b+1)(1+a)+ab]/c
Any help would be appreciated.
Well, my advice is first isolate the numerator, then get the quotient and remainder after dividing by b + 1, then put the pieces back together.
(%i1) display2d : false $
(%i2) expr : (b + 2*a*b + a + 1)/c $
(%i3) num (expr);
(%o3) 2*a*b+b+a+1
(%i4) divide (num (expr), b + 1);
(%o4) [2*a+1,-a]
(%i5) first(%o4) * (b + 1) + second(%o4);
(%o5) (2*a+1)*(b+1)-a
(%i6) (first(%o4) * (b + 1) + second(%o4)) / denom (expr);
(%o6) ((2*a+1)*(b+1)-a)/c
(%i7) is (equal (%o6, expr));
(%o7) true
Note that divide returns two values; first is the quotient and second is the remainder.

Resources