Compound Expressions in a Function in Mathematica - wolfram-mathematica

I wanted to calculate the power sum S_p(x) = 1^p + 2^p + 3^p + ... + x^p using the code
powersum[x_,p_]:=sum=0;For[i=1,i<x,i++,sum=sum+i^p];sum
but it seems to output 0 every time. Why does it do that?

As written, Mathematica is parsing your expression like this:
powersum[x_,p_]:=sum=0; (*Definition ended here*)
For[i=1,i<x,i++,sum=sum+i^p];
sum
You need to use to wrap your expression in parenthesis to make them all part of the function definition.
powersum[x_,p_]:=(sum=0;For[i=1,i<x,i++,sum=sum+i^p];sum)

Often it is preferable to use Module[]:
powersum[x_,p_]:=Module[{sum},sum=0;For[i=1,i<x,i++,sum=sum+i^p];sum]
or
powersum[x_,p_]:=Module[{sum=0},For[i=1,i<x,i++,sum=sum+i^p];sum]
this is essentially the same as wrapping in () except sum is protected in a local context.
of course for this example you could as well use :
powersum[x_,p_]:=Sum[i^p,{i,1,x-1}]
or
powersum[x_, p_] := Range[x - 1]^p // Total

Related

TypeError using pmap in Julia 1.6.1

I have been working to parallelize a function which reads in an input of polynomials and outputs their roots. The polynomials are in the form of a matrix with columns being each polynomial. It works perfectly fine calling directly, but I get strange behaviour once I use pmap.
using Distributed
#everywhere begin
using PolynomialRoots
end
addprocs(2)
#everywhere global test = ones(Int64, 10,10)
#everywhere begin
function polyRootS(n)
q=test[:,n]
r = roots(q) # provides poly roots from a vector input
return r
end
end
function parPolyRoots()
pmap(x->polyRootS(x) ? error("failed") : x, 1:10; on_error=identity)
end
for i in 1:10
r = polyRootS(i)
println(r)
end
parPolyRoots()
As far as I have read pmap should in effect just be parallelizing the loop when calling polyRootS yet I instead get the outputs:
ComplexF64[0.30901699437494734 + 0.9510565162951534im, 0.8090169943749473 - 0.587785252292473im, -0.8090169943749473 - 0.587785252292473im, -0.8090169943749475 + 0.587785252292473im, 0.8090169943749475 + 0.5877852522924731im, 0.30901699437494745 - 0.9510565162951535im, -1.0 - 7.671452424696258e-18im, -0.30901699437494734 - 0.9510565162951536im, -0.3090169943749474 + 0.9510565162951536im]
for my test matrix and
TypeError(:if, "", Bool, ComplexF64[0.30901699437494734 + 0.9510565162951534im, 0.8090169943749473 - 0.587785252292473im, -0.8090169943749473 - 0.587785252292473im, -0.8090169943749475 + 0.587785252292473im, 0.8090169943749475 + 0.5877852522924731im, 0.30901699437494745 - 0.9510565162951535im, -1.0 - 7.671452424696258e-18im, -0.30901699437494734 - 0.9510565162951536im, -0.3090169943749474 + 0.9510565162951536im])
for my pmap function call. So I am quite puzzled. If someone could point me to some different documentation for pmap and or a few examples that would be especially helpful.
A different question, can I start an #everything begin end statement and cover my defined functions, data, and packages at once or is it best practice to individually isolate them?
Using Julia 1.6.1 in VSCode with Julia extension. Running on Win10 with Intel i5.
The problem is not to do with pmap, it's because of the anonymous function you've defined to be its first argument:
x->polyRootS(x) ? error("failed") : x
If you look at the TypeError (and refer the docs about TypeError's syntax), you can see that it's complaining that it was expecting a Bool and instead got a ComplexF64 array. The left side of the ? in the ternary operator is equivalent to an if condition, and Julia expects a Boolean value there. Instead, the call to polyRootS is returning a ComplexF64[] value.
It's not clear what you're trying to check there either. Your polyRootS definition doesn't return any error indicator return value, and any exceptions will be handled by the on_error argument already.
So, replacing that anonymous function with just polyRootS as the first argument to pmap should work.

Is there a way to use range with Z3ints in z3py?

I'm relatively new to Z3 and experimenting with it in python. I've coded a program which returns the order in which different actions is performed, represented with a number. Z3 returns an integer representing the second the action starts.
Now I want to look at the model and see if there is an instance of time where nothing happens. To do this I made a list with only 0's and I want to change the index at the times where each action is being executed, to 1. For instance, if an action start at the 5th second and takes 8 seconds to be executed, the index 5 to 12 would be set to 1. Doing this with all the actions and then look for 0's in the list would hopefully give me the instances where nothing happens.
The problem is: I would like to write something like this for coding the problem
list_for_check = [0]*total_time
m = s.model()
for action in actions:
for index in range(m.evaluate(action.number) , m.evaluate(action.number) + action.time_it_takes):
list_for_check[index] = 1
But I get the error:
'IntNumRef' object cannot be interpreted as an integer
I've understood that Z3 isn't returning normal ints or bools in their models, but writing
if m.evaluate(action.boolean):
works, so I'm assuming the if is overwritten in a way, but this doesn't seem to be the case with range. So my question is: Is there a way to use range with Z3 ints? Or is there another way to do this?
The problem might also be that action.time_it_takes is an integer and adding a Z3int with a "normal" int doesn't work. (Done in the second part of the range).
I've also tried using int(m.evaluate(action.number)), but it doesn't work.
Thanks in advance :)
When you call evaluate it returns an IntNumRef, which is an internal z3 representation of an integer number inside z3. You need to call as_long() method of it to convert it to a Python number. Here's an example:
from z3 import *
s = Solver()
a = Int('a')
s.add(a > 4);
s.add(a < 7);
if s.check() == sat:
m = s.model()
print("a is %s" % m.evaluate(a))
print("Iterating from a to a+5:")
av = m.evaluate(a).as_long()
for index in range(av, av + 5):
print(index)
When I run this, I get:
a is 5
Iterating from a to a+5:
5
6
7
8
9
which is exactly what you're trying to achieve.
The method as_long() is defined here. Note that there are similar conversion functions from bit-vectors and rationals as well. You can search the z3py api using the interface at: https://z3prover.github.io/api/html/namespacez3py.html

Javascript Function syntax in plain English

I'm a part-time English teacher and I want to teach students basic programming so I try to rewrite syntax into plain English for them to understand more easily.
So I rewrite Javascript:
function functionName(a, b, c) {
// actual function
return a + b + c
};
functionName(1,2,3);
as plain English:
formula formulaName(input1, input2, input3) {
// actual formula
run input1 + input2 + input3
};
// without the formula keyword it means execute
// with the formula keyword it means define:
formulaName(1,2,3);
// formula that assigns 1,2,3 as input1, input2, input3, then adds them to get the output when executed
Is my english translation correct?
I'd reckon to call it function instead of formula. A function can do more things than a formula itself. A formula is something applied on one or more expressions whereas a function can contain more than one formula, even an output of a formula can be used as an input for another formula within the same function. Also, the keyword execute make more sense than run. You can also use the keyword statement to refer each expression. There is nothing wrong as long as syntactical pseudo code is correct.

How can I define an abstract odd function in mathematica? With respect to derivatives

I want "to work symbolically" but not only with function but with derivatives. For instance I would like
f'[x] - f'[-x]
to be simplified to zero.
Comment: Neither of the ways, suggested here, did not help me.
They kind of works but now you need to create rules for Derivative not to f really. And since Derivative is not even protected you can do something like:
Derivative[n_][f][-x_] := -Derivative[n][f][x]
f''[x] + f'''''''[-x] + f''[-x] + f[x] + f'''''''[x]
f[x]
is this ok?

How do I make a function use the altered version of a list in Mathematica?

I want to make a list with its elements representing the logic map given by
x_{n+1} = a*x_n(1-x_n)
I tried the following code (which adds stuff manually instead of a For loop):
x0 = Input["Enter x0"]
a = Input["a"]
M = {x0}
L[n_] := If[n < 1, x0, a*M[[n]]*(1 - M[[n]])]
Print[L[1]]
Append[M, L[1]]
Print[M]
Append[M, L[2]]
Print[M]
The output is as follows:
0.3
2
{0.3}
0.42
{0.3,0.42}
{0.3}
Part::partw: Part 2 of {0.3`} does not exist. >>
Part::partw: Part 2 of {0.3`} does not exist. >>
{0.3, 2 (1 - {0.3}[[2]]) {0.3}[[2]]}
{0.3}
It seems that, when the function definition is being called in Append[M,L[2]], L[2] is calling M[[2]] in the older definition of M, which clearly does not exist.
How can I make L use the newer, bigger version of M?
After doing this I could use a For loop to generate the entire list up to a certain index.
P.S. I apologise for the poor formatting but I could find out how to make Latex code work here.
Other minor question: What are the allowed names for functions and lists? Are underscores allowed in names?
It looks to me as if you are trying to compute the result of
FixedPointList[a*#*(1-#)&, x0]
Note:
Building lists element-by-element, whether you use a loop or some other construct, is almost always a bad idea in Mathematica. To use the system productively you need to learn some of the basic functional constructs, of which FixedPointList is one.
I'm not providing any explanation of the function I've used, nor of the interpretation of symbols such as # and &. This is all covered in the documentation which explains matters better than I can and with which you ought to become familiar.
Mathematica allows alphanumeric (only) names and they must start with a letter. Of course, Mathematic recognises many Unicode characters other than the 26 letters in the English alphabet as alphabetic. By convention (only) intrinsic names start with an upper-case letter and your own with a lower-case.
The underscore is most definitely not allowed in Mathematica names, it has a specific and widely-used interpretation as a short form of the Blank symbol.
Oh, LaTeX formatting doesn't work hereabouts, but Mathematica code is plenty readable enough.
It seems that, when the function definition is being called in
Append[M,L2], L2 is calling M[2] in the older definition of M,
which clearly does not exist.
How can I make L use the newer, bigger version of M?
M is never getting updated here. Append does not modify the parameters you pass to it; it returns the concatenated value of the arrays.
So, the following code:
A={1,2,3}
B=Append[A,5]
Will end up with B={1,2,3,5} and A={1,2,3}. A is not modfied.
To analyse your output,
0.3 // Output of x0 = Input["Enter x0"]. Note that the assignment operator returns the the assignment value.
2 // Output of a= Input["a"]
{0.3} // Output of M = {x0}
0.42 // Output of Print[L[1]]
{0.3,0.42} // Output of Append[M, L[1]]. This is the *return value*, not the new value of M
{0.3} // Output of Print[M]
Part::partw: Part 2 of {0.3`} does not exist. >> // M has only one element, so M[[2]] doesn't make sense
Part::partw: Part 2 of {0.3`} does not exist. >> // ditto
{0.3, 2 (1 - {0.3}[[2]]) {0.3}[[2]]} (* Output of Append[M, L[2]]. Again, *not* the new value of M *)
{0.3} // Output of Print[M]
The simple fix here is to use M=Append[M, L[1]].
To do it in a single for loop:
xn=x0;
For[i = 0, i < n, i++,
M = Append[M, xn];
xn = A*xn (1 - xn)
];
A faster method would be to use NestList[a*#*(1-#)&, x0,n] as a variation of the method mentioned by Mark above.
Here, the expression a*#*(1-#)& is basically an anonymous function (# is its parameter, the & is a shorthand for enclosing it in Function[]). The NestList method takes a function as one argument and recursively applies it starting with x0, for n iterations.
Other minor question: What are the allowed names for functions and lists? Are underscores allowed in names?
No underscores, they're used for pattern matching. Otherwise a variable can contain alphabets and special characters (like theta and all), but no characters that have a meaning in mathematica (parentheses/braces/brackets, the at symbol, the hash symbol, an ampersand, a period, arithmetic symbols, underscores, etc). They may contain a dollar sign but preferably not start with one (these are usually reserved for system variables and all, though you can define a variable starting with a dollar sign without breaking anything).

Resources