Can I define a maxima function f(x) which assigns to the argument x - function

Sorry for the basic question, but it's quite hard to find too much discussion on Maxima specifics.
I'm trying to learn some Maxima and wanted to use something like
x:2
x+=2
which as far as I can tell doesn't exist in Maxima. Then I discovered that I can define my own operators as infix operators, so I tried doing
infix("+=");
"+=" (a,b):= a:(a+b);
However this doesn't work, as if I first set x:1 then try calling x+=2, the function returns 3, but if I check the value of x I see it hasn't changed.
Is there a way to achieve what I was trying to do in Maxima? Could anyone explain why the definition I gave fails?
Thanks!

The problem with your implementation is that there is too much and too little evaluation -- the += function doesn't see the symbol x so it doesn't know to what variable to assign the result, and the left-hand side of an assignment isn't evaluated, so += thinks it is assigning to a, not x.
Here's one way to get the right amount of evaluation. ::= defines a macro, which is just a function which quotes its arguments, and for which the return value is evaluated again. buildq is a substitution function which quotes the expression into which you are substituting. So the combination of ::= and buildq here is to construct the x: x + 2 expression and then evaluate it.
(%i1) infix ("+=") $
(%i2) "+="(a, b) ::= buildq ([a, b], a: a + b) $
(%i3) x: 100 $
(%i4) macroexpand (x += 1);
(%o4) x : x + 1
(%i5) x += 1;
(%o5) 101
(%i6) x;
(%o6) 101
(%i7) x += 1;
(%o7) 102
(%i8) x;
(%o8) 102
So it is certainly possible to do so, if you want to do that. But may I suggest maybe you don't need it? Modifying a variable makes it harder to keep track, mentally, what is going on. A programming policy such as one-time assignment can make it easier for the programmer to understand the program. This is part of a general approach called functional programming; perhaps you can take a look at that. Maxima has various features which make it possible to use functional programming, although you are not required to use them.

Related

Mathematica Integration taking too long

Using Mathematica I need to evaluate the integral of a function. Since it is taking the program too much to compute it, would it be possible to use parallel computation to shorten the time needed? If so, how can I do it?
I uploaded a picture of the integrand function:
I need to integrate it with respect to (x3, y3, x, y) all of them ranging in a certain interval (x3 and y3 from 0 to 1) (x and y from 0 to 100). The parameters (a,b,c...,o) are preventing the NIntegrate function to work. Any suggestions?
If you evaluate this
expr=E^((-(x-y)^4-(x3-y3)^4)/10^4)*
(f x+e x^2+(m+n x)x3-f y-e y^2-(m+n y)y3)*
((378(x-y)^2(f x+e x^2+(m+n x)x3-f y-e y^2-(m+n y)y3))/
(Pi(1/40+Sqrt[((x-y)^2+(x3-y3)^2)^3]))+
(378(x-y)(x3-y3)(h x+g x^2+(o+p x)x3-h y-g y^2-(o+p y)y3))/
(Pi(1/40+Sqrt[((x-y)^2+(x3-y3)^2)^3])))+
(h x+g x^2+(o+p x)x3-h y-g y^2-(o +p y) y3)*
((378(x-y)(x3-y3)(f x+e x^2+(m+n x)x3-f y-e y^2-(m+n y)y3))/
(Pi(1/40+Sqrt[((x-y)^2+(x3-y3)^2)^3]))+
(378 (x3 - y3)^2 (h x + g x^2 + (o + p x)x3-h y-g y^2-(o+p y)y3))/
(Pi(1/40+Sqrt[((x-y)^2+(x3-y3)^2)^3])));
list=List ## Expand[expr]
then you will get a list of 484 expressions, each very similar in form to this
(378*f*h*x^3*x3)/(Pi*(1/40+Sqrt[(x^2+x3^2-2*x*y+y^2-2*x3*y3+y3^2)^3]))
Notice that you can then use NIntegrate in this way
f*h*NIntegrate[(378*x^3*x3)/(Pi*(1/40+Sqrt[(x^2+x3^2-2*x*y+y^2-2*x3*y3+y3^2)^3])),
{x,0,100},{y,0,100},{x3,0,1},{y3,0,1}]
but it gives warnings and errors about the convergence and accuracy, almost certainly due to your fractional powers in the denominator.
If you can find a way to pull out the scalar multipliers which are independent of x,y,x3,y3 and then perform that integration without warnings and errors and get an accurate result which isn't infinity then you could perhaps perform these integrals in parallel and total the results.
Some of the integrands are scalar multiples of others and if you combine similar integrands then you can reduce this down to 300 unique integrands.
I doubt this is going to lead to an acceptable solution for you.
Please check all this very carefully to make certain that no mistakes have been made.
EDIT
Since the variables that are independent of the integration appear to be easily separated from the dependent variables in the problem posed above, I think this will allow parallel NIntegrate
independentvars[z_] := (z/(z//.{e->1, f->1, g->1, h->1, m->1, n->1, o->1, p->1}))*
NIntegrate[(z//.{e->1, f->1, g->1, h->1, m->1, n->1, o->1, p->1}),
{x, 0, 100}, {y, 0, 100}, {x3, 0, 1}, {y3, 0, 1}]
Total[ParallelMap[independentvars, list]]
As I mentioned previously, the fractional powers in the denominator result in a flood of warnings and errors about convergence failing.
You can test this with the following much simpler example
expr = f x + f g x3 + o^2 x x3;
list = List ## Expand[expr];
Total[ParallelMap[independentvars, list]]
which instantly returns
500000. f + 5000. f g + 250000. o^2
This is a very primitive method of pulling independent symbolic variables outside an NIntegrate. This gives absolutely no warning if one of the integrands is not in a form where this primitive attempt at extraction is not appropriate or fails.
There may be a far better method that someone else has written out there somewhere. If someone could show a far better method of doing this then I would appreciate it.
It might be nice if Wolfram would consider incorporating something like this into NIntegrate itself.

Is it possible to write (display) exponential equations in scilab?

I've been trying to display in my console an exponential equation like the following one:
y(t) = a*e^t + b*e^t + c*e^t
I would write it as a string, however the coefficients a,b and c, are numbers in a vector V = [a b c]. So I was trying to concatenate the numbers with strings "e^t", but I failed to do it. I know scilab displays polynomial equations, but I don't know it is possible to display exponential one. Anyone can help?
Usually this kind of thing is done with mprintf command, which places given numerical arguments into a string with formatting instructions.
V = [3 5 -7]
mprintf("y(t) = %f*e^t + %f*e^t + %f*e^t", V)
The output is
y(t) = 3.000000*e^t + 5.000000*e^t + -7.000000*e^t
which isn't ideal, and can be improved in some ways by tweaking the formatters, but is readable regardless.
Notice we don't have to list every entry V(1), V(2), ... individually; the vector V gets "unpacked" automatically.
If you wanted to have 2D output like what we get for polynomials,
then no, this kind of thing is what Scilab does for polynomials and rational functions only, not for general expressions.
There is also prettyprint but its output is LaTeX syntax, like $1+s+s^{2}-s^{123}$. It works for a few things: polynomials, rational functions, matrices... but again, Scilab is not meant for symbolic manipulations, and does not really support symbolic expressions.

Haskell - lambda expression

I am trying to understand what's useful and how to actually use lambda expression in Haskell.
I don't really understand the advantage of using lambda expression over the convention way of defining functions.
For example, I usually do the following:
let add x y = x+y
and I can simply call
add 5 6
and get the result of 11
I know I can also do the following:
let add = \x->(\y-> x+y)
and get the same result.
But like I mentioned before, I don't understand the purpose of using lambda expression.
Also, I typed the following code (a nameless function?) into the prelude and it gave me an error message.
let \x -> (\y->x+y)
parse error (possibly incorrect indentation or mismatched backets)
Thank you in advance!
Many Haskell functions are "higher-order functions", i.e., they expect other functions as parameters. Often, the functions we want to pass to such a higher-order function are used only once in the program, at that particular point. It's simply more convenient then to use a lambda expression than to define a new local function for that purpose.
Here's an example that filters all even numbers that are greater than ten from a given list:
ghci> filter (\ x -> even x && x > 10) [1..20]
[12,14,16,18,20]
Here's another example that traverses a list and for every element x computes the term x^2 + x:
ghci> map (\ x -> x^2 + x) [1..10]
[2,6,12,20,30,42,56,72,90,110]

Compute real roots of a quadratic equation in Pascal

I am trying to solve this problem :
(Write a program to compute the real roots of a quadratic equation (ax2 + bx + c = 0). The roots can be calculated using the following formulae:
x1 = (-b + sqrt(b2 - 4ac))/2a
and
x2 = (-b - sqrt(b2 - 4ac))/2a
I wrote the following code, but its not correct:
program week7_lab2_a1;
var a,b,c,i:integer;
x,x1,x2:real;
begin
write('Enter the value of a :');
readln(a);
write('Enter the value of b :');
readln(b);
write('Enter the value of c :');
readln(c);
if (sqr(b)-4*a*c)>=0 then
begin
if ((a>0) and (b>0)) then
begin
x1:=(-1*b+sqrt(sqr(b)-4*a*c))/2*a;
x2:=(-1*b-sqrt(sqr(b)-4*a*c))/2*a;
writeln('x1=',x1:0:2);
writeln('x2=',x2:0:2);
end
else
if ((a=0) and (b=0)) then
write('The is no solution')
else
if ((a=0) and (b<>0)) then
begin
x:=-1*c/b;
write('The only root :',x:0:2);
end;
end
else
if (sqr(b)-4*a*c)<0 then
write('The is no real root');
readln;
end.
do you know why?
and taking a=-6,b=7,c=8 .. can you desk-check it after writing the pesudocode?
You have an operator precedence error here:
x1:=(-1*b+sqrt(sqr(b)-4*a*c))/2*a;
x2:=(-1*b-sqrt(sqr(b)-4*a*c))/2*a;
See at the end, the 2 * a doesn't do what you think it does. It does divide the expression by 2, but then multiplies it by a, because of precedence rules. This is what you want:
x1:=(-1*b+sqrt(sqr(b)-4*a*c))/(2*a);
x2:=(-1*b-sqrt(sqr(b)-4*a*c))/(2*a);
In fact, this is because the expression is evaluated left-to-right wrt brackets and that multiplication and division have the same priority. So basically, once it's divided by 2, it says "I'm done with division, I will multiply what I have now with a as told".
As it doesn't really seem clear from the formula you were given, this is the quadratic formula:
As you can see you need to divide by 2a, so you must use brackets here to make it work properly, just as the correct text-only expression for this equation is x = (-b +- sqrt(b^2 - 4ac)) / (2a).
Otherwise the code looks fine, if somewhat convoluted (for instance, you could discard cases where (a = 0) and (b = 0) right after input, which would simplify the logic a bit later on). Did you really mean to exclude negative coefficients though, or just zero coefficients? You should check that.
Also be careful with floating-point equality comparison - it works fine with 0, but will usually not work with most constants, so use an epsilon instead if you need to check if one value is equal to another (like such: abs(a - b) < 1e-6)
Completely agree with what Thomas said in his answer. Just want to add some optimization marks:
You check the discriminant value in if-statement, and then use it again:
if (sqr(b)-4*a*c)>=0 then
...
x1:=(-1*b+sqrt(sqr(b)-4*a*c))/2*a;
x2:=(-1*b-sqrt(sqr(b)-4*a*c))/2*a;
This not quite efficient - instead of evaluating discriminant value at once you compute it multiple times. You should first compute discriminant value and store it into some variable:
D := sqr(b)-4*a*c;
and after that you can use your evaluated value in all expressions, like this:
if (D >= 0) then
...
x1:=(-b+sqrt(D)/(2*a);
x2:=(-b-sqrt(D)/(2*a);
and so on.
Also, I wouldn't write -1*b... Instead of this just use -b or 0-b in worst case, but not multiplication. Multiplication here is not needed.
EDIT:
One more note:
Your code:
if (sqr(b)-4*a*c)>=0 then
begin
...
end
else
if (sqr(b)-4*a*c)<0 then
write('The is no real root');
You here double check the if-condition. I simplify this:
if (a) then
begin ... end
else
if (not a)
...
Where you check for not a (in your code it corresponds to (sqr(b)-4*a*c)<0) - in this case condition can be only false (for a) and there is no need to double check it. You should just throw it out.

Function types declarations in Mathematica

I have bumped into this problem several times on the type of input data declarations mathematica understands for functions.
It Seems Mathematica understands the following types declarations:
_Integer,
_List,
_?MatrixQ,
_?VectorQ
However: _Real,_Complex declarations for instance cause the function sometimes not to compute. Any idea why?
What's the general rule here?
When you do something like f[x_]:=Sin[x], what you are doing is defining a pattern replacement rule. If you instead say f[x_smth]:=5 (if you try both, do Clear[f] before the second example), you are really saying "wherever you see f[x], check if the head of x is smth and, if it is, replace by 5". Try, for instance,
Clear[f]
f[x_smth]:=5
f[5]
f[smth[5]]
So, to answer your question, the rule is that in f[x_hd]:=1;, hd can be anything and is matched to the head of x.
One can also have more complicated definitions, such as f[x_] := Sin[x] /; x > 12, which will match if x>12 (of course this can be made arbitrarily complicated).
Edit: I forgot about the Real part. You can certainly define Clear[f];f[x_Real]=Sin[x] and it works for eg f[12.]. But you have to keep in mind that, while Head[12.] is Real, Head[12] is Integer, so that your definition won't match.
Just a quick note since no one else has mentioned it. You can pattern match for multiple Heads - and this is quicker than using the conditional matching of ? or /;.
f[x:(_Integer|_Real)] := True (* function definition goes here *)
For simple functions acting on Real or Integer arguments, it runs in about 75% of the time as the similar definition
g[x_] /; Element[x, Reals] := True (* function definition goes here *)
(which as WReach pointed out, runs in 75% of the time
as g[x_?(Element[#, Reals]&)] := True).
The advantage of the latter form is that it works with Symbolic constants such as Pi - although if you want a purely numeric function, this can be fixed in the former form with the use of N.
The most likely problem is the input your using to test the the functions. For instance,
f[x_Complex]:= Conjugate[x]
f[x + I y]
f[3 + I 4]
returns
f[x + I y]
3 - I 4
The reason the second one works while the first one doesn't is revealed when looking at their FullForms
x + I y // FullForm == Plus[x, Times[ Complex[0,1], y]]
3 + I 4 // FullForm == Complex[3,4]
Internally, Mathematica transforms 3 + I 4 into a Complex object because each of the terms is numeric, but x + I y does not get the same treatment as x and y are Symbols. Similarly, if we define
g[x_Real] := -x
and using them
g[ 5 ] == g[ 5 ]
g[ 5. ] == -5.
The key here is that 5 is an Integer which is not recognized as a subset of Real, but by adding the decimal point it becomes Real.
As acl pointed out, the pattern _Something means match to anything with Head === Something, and both the _Real and _Complex cases are very restrictive in what is given those Heads.