get the expression out of solve results - maxima

Cosider the simple solution:
sol: solve(b * x - a, x);
a
[x = -]
b
how can I get the expression part sol: a / b out of the above result?
solution was offered to me here.

Thanks to Johann Weilharter I found one way to extract the expression:
sol: ev(x, solve(b * x - a, x)[1]);
Of course, if there is more than one solution, you need to change 1 to the specific instance.
Alternatively, as pointed out in the comments of the question, one can also use
sol: rhs(first(solve(b * x - a, x)));
oneliner to do the job.

What you need is a symbolic evaluation library. If you are considering a python implementation, you can use SymPy.
import sympy as sym
x = sym.Symbol('x')
b = sym.Symbol('b')
a = sym.Symbol('a')
sol = sym.solve((b * x - a), x)
print(sol)
------
[a/b]

Related

Take out common variables using Z3

I have a formlua in DNF form, say:
abcx + abcy + abz
Is there any way to take out the common variables, to get the follwing formula:
ab (cx + cy + z)
A followup question, can it be done recursively, like
ab ( c(x+y) + z)
Sure.. Here's one way:
from z3 import *
a, b, c, x, y, z = Ints('a b c x y z')
print simplify(a*b*c*x + a*b*c*y + a*b*z, hoist_mul=True)
This prints:
a*b*(c*(x + y) + z)
which is exactly what you're looking for.
And for your next question, how did I find about hoist_cmul=True argument? Simply run:
help_simplify()
at your Python prompt, and it'll list you all the options simplify takes.
Note that you should in general not count on what the simplifier will give you. It's mostly heuristic driven, and in the presence of other terms what you get may not match what you expected. (It'll of course still be an equivalent expression.) There's no notion of "simplest" when it comes to arithmetic expressions, and what you consider simple and what z3 considers simple may not necessarily match.

SUMPRODUCT in F# without variables

I have already done some searches, and this question is a duplicate of another post. I am posting this just for future reference.
Is it possible to define SUMPRODUCT without explicitly using variable names x, y?
Original Function:
let SUMPRODUCT x y = List.map2 (*) x y |> List.sum
SUMPRODUCT [1;4] [3;25] // Result: 103
I was hoping to do this:
// CONTAINS ERROR!
let SUMPRODUCT = (List.map2 (*)) >> List.sum
// CONTAINS ERROR!
But F# comes back with an error.
I have already found the solution on another post, but if you have any suggestions please let me know. Thank you.
Function composition only works when the input function takes a single argument. However, in your example, the result of List.map2 (*) is a function that takes two separate arguments and so it cannot be easily composed with List.sum using >>.
There are various ways to work around this if you really want, but I would not do that. I think >> is nice in a few rare cases where it fits nicely, but trying to over-use it leads to unreadable mess.
In some functional languages, the core library defines helpers for turning function with two arguments into a function that takes a tuple and vice versa.
let uncurry f (x, y) = f x y
let curry f x y = f (x, y)
You could use those two to define your sumProduct like this:
let sumProduct = curry ((uncurry (List.map2 (*))) >> List.sum)
Now it is point-free and understanding it is a fun mental challenge, but for all practical purposes, nobody will be able to understand the code and it is also longer than your original explicit version:
let sumProduct x y = List.map2 (*) x y |> List.sum
According to this post:
What am I missing: is function composition with multiple arguments possible?
Sometimes "pointed" style code is better than "pointfree" style code, and there is no good way to unify the type difference of the original function to what I hope to achieve.

Check if answer is from specific form

I want to check if some maxima input is of a specific form. For example, I want to check if the answer is of the form A*%e^(B*t) where A and B are specific real numbers.
If student X gives answer 3*%e^(5*t), then it is of this form. If student Y gives answer sin(t), or maybe y=3*%e^(5*t) then I can give this student as feedback that his answer is not yet of the correct form.
I was wondering if there exist something like this in maxima.
Maxima has several pattern-matching functions that operate on expressions (not strings). I think defmatch is suitable here, e.g.:
(%i8) matchdeclare ([A, B], constantp);
(%o8) done
(%i9) defmatch (match_aexpbt, A*exp(B*t), t);
(%o9) match_aexpbt
(%i10) match_aexpbt (5*exp(3*u), u);
(%o10) [A = 5, B = 3, t = u]
(%i11) match_aexpbt (sqrt(2)*exp(%pi*z), z);
(%o11) [A = sqrt(2), B = %pi, t = z]
(%i12) match_aexpbt (y = 5*exp(3*u), u);
(%o12) false
(%i13) match_aexpbt (5*sin(2*u), u);
(%o13) false
(%i14) match_aexpbt ((1 + %i)*exp(exp(%pi)*v), v);
%pi
(%o14) [A = %i + 1, B = %e , t = v]
In this case I've defined match_aexpbt which matches expressions which look like A*exp(B*t) where A and B are constants and t is a variable which is supplied.
See the documentation for defmatch and matchdeclare and also defrule, tellsimp, and tellsimpafter. The pattern-matching functions are a little idiosyncratic but actually pretty useful -- I have used them many times.
If you are interested in checking student's answers, there have been projects based on Maxima for that. Take a look at the related projects webpage and see in particular STACK.

How to prove commutative property for rational number in Agda?

I am trying to prove commutative property for agda. I tried to explore the standard library but there is lot of complex thing which i could not understand.
I tried in this way --
comm : (a b : Q) -> (a + b) === (b + a)
the problem here is + which is not defined over Q in library. Can't we proof this without defining + over Q.
Please guide me.
You cannot prove this without first defining +.
If you get confused exploring the standard library I suggest you try to prove something easier first, in order to become more acquainted with Agda, before tackling this.
Of course you can't prove commutativity of an undefined function _+_; as a stupid counter-example, would you expect to be able to prove (a - b) == (b - a)? If not, why not? _-_ is just as much of an undefined function as _+_ at this point; it just has a different name...
Note that you can define addition for ℚ using elementary school math:
n ÷ p + m ÷ q = (n * q + m * p) ÷ (p * q)
and simplifying it by dividing both n * q + m * p and p * q with their GCD. I have already explained the details of this last step in this answer.

How do I do convolution in F#?

I would like convolve a discrete signal with a discrete filter. The signal and filter is sequences of float in F#.
The only way I can figure out how to do it is with two nested for loops and a mutable array to store the result, but it does not feel very functional.
Here is how I would do it non-functional:
conv = double[len(signal) + len(filter) - 1]
for i = 1 to len(signal)
for j = 1 to len(filter)
conv[i + j] = conv[i + j] + signal(i) * filter(len(filter) - j)
I don't know F#, but I'll post some Haskell and hopefully it will be close enough to use. (I only have VS 2005 and an ancient version of F#, so I think it would be more confusing to post something that works on my machine)
Let me start by posting a Python implementation of your pseudocode to make sure I'm getting the right answer:
def convolve(signal, filter):
conv = [0 for _ in range(len(signal) + len(filter) - 1)]
for i in range(len(signal)):
for j in range(len(filter)):
conv[i + j] += signal[i] * filter[-j-1]
return conv
Now convolve([1,1,1], [1,2,3]) gives [3, 5, 6, 3, 1]. If this is wrong, please tell me.
The first thing we can do is turn the inner loop into a zipWith; we're essentially adding a series of rows in a special way, in the example above: [[3,2,1], [3,2,1], [3,2,1]]. To generate each row, we'll zip each i in the signal with the reversed filter:
makeRow filter i = zipWith (*) (repeat i) (reverse filter)
(Note: according to a quick google, zipWith is map2 in F#. You might have to use a list comprehension instead of repeat)
Now:
makeRow [1,2,3] 1
=> [3,2,1]
makeRow [1,2,3] 2
=> [6,4,2]
To get this for all i, we need to map over signal:
map (makeRow filter) signal
=> [[3,2,1], [3,2,1], [3,2,1]]
Good. Now we just need a way to combine the rows properly. We can do this by noticing that combining is adding the new row to the existing array, except for the first element, which is stuck on front. For example:
[[3,2,1], [6,4,2]] = 3 : [2 + 6, 1 + 4] ++ [2]
// or in F#
[[3; 2; 1]; [6; 4; 2]] = 3 :: [2 + 6; 1 + 4] # [2]
So we just need to write some code that does this in the general case:
combine (front:combinable) rest =
let (combinable',previous) = splitAt (length combinable) rest in
front : zipWith (+) combinable combinable' ++ previous
Now that we have a way to generate all the rows and a way to combine a new row with an existing array, all we have to do is stick the two together with a fold:
convolve signal filter = foldr1 combine (map (makeRow filter) signal)
convolve [1,1,1] [1,2,3]
=> [3,5,6,3,1]
So that's a functional version. I think it's reasonably clear, as long as you understand foldr and zipWith. But it's at least as long as the imperative version and like other commenters said, probably less efficient in F#. Here's the whole thing in one place.
makeRow filter i = zipWith (*) (repeat i) (reverse filter)
combine (front:combinable) rest =
front : zipWith (+) combinable combinable' ++ previous
where (combinable',previous) = splitAt (length combinable) rest
convolve signal filter = foldr1 combine (map (makeRow filter) signal)
Edit:
As promised, here is an F# version. This was written using a seriously ancient version (1.9.2.9) on VS2005, so be careful. Also I couldn't find splitAt in the standard library, but then I don't know F# that well.
open List
let gen value = map (fun _ -> value)
let splitAt n l =
let rec splitter n l acc =
match n,l with
| 0,_ -> rev acc,l
| _,[] -> rev acc,[]
| n,x::xs -> splitter (n - 1) xs (x :: acc)
splitter n l []
let makeRow filter i = map2 ( * ) (gen i filter) (rev filter)
let combine (front::combinable) rest =
let combinable',previous = splitAt (length combinable) rest
front :: map2 (+) combinable combinable' # previous
let convolve signal filter =
fold1_right combine (map (makeRow filter) signal)
Try this function:
let convolute signal filter =
[|0 .. Array.length signal + Array.length filter - 1|] |> Array.map (fun i ->
[|0 .. i|] |> Array.sum_by (fun j -> signal.[i] * filter.[Array.length filter - (i - j) - 1]))
It's probably not the nicest function solution, but it should do the job. I doubt there exists a purely functional solution that will match the imperative one for speed however.
Hope that helps.
Note: The function is currently untested (though I've confirmed it compiles). Let me know if it doesn't quite do what it should. Also, observe that the i and j variables do not refer to the same things as is your original post.
Indeed, you generally want to avoid loops (plain, nested, whatever) and anything mutable in functional programming.
There happens to be a very simple solution in F# (and probably almost every other functional language):
let convolution = Seq.zip seq1 seq2
The zip function simply combines the two sequences into one of pairs containing the element from seq1 and the element from seq2. As a note, there also exist similar zip functions for the List and Array modules, as well as variants for combining three lists into triples (zip3). If you want tom ore generally zip (or "convolute") n lists into a list of n-tuples, then you'll need to write your own function, but it's pretty straightforward.
(I've been going by this description of convolution by the way - tell me if you mean something else.)
In principle, it should be possible to use the (Fast) Fourier Transform, or the related (Discrete) Cosine Transform, to calculate the convolution of two functions reasonably efficiently. You calculate the FFT for both functions, multiply them, and apply the inverse FFT on the result.
mathematical background
That's the theory. In practice you'd probably best find a math library that implements it for you.

Resources