Maple: RNG is not random - maple

i was "finding Pi" with Monte Carlo Method, but the answer was incorrect. The oryginal code was:
RandomTools[MersenneTwister]: with(Statistics):
tries := 10000:
s := 0;
for i to tries do
if GenerateFloat()^2+GenerateFloat()^2 < 1 then s := s+1 end if;
end do:
evalf(4*s/tries)
It gives answer aroud 2.8-2.85
when I change the code to
s := 0;
x := Array([seq(GenerateFloat(), i = 1 .. tries)]);
y := Array([seq(GenerateFloat(), i = 1 .. tries)]);
for i to tries do
if x[i]^2+y[i]^2 < 1 then s := s+1 end if;
end do:
evalf(4*s/tries)
Then the answer is correct. I have no idea why i can't generate number in "for" loop.
I've founded that the mean of it is the same, but the variance is different.
For:
tries := 100000;
A := Array([seq(GenerateFloat(), i = 1 .. 2*tries)]);
s1 := Array([seq(A[i]^2+A[tries+i]^2, i = 1 .. tries)]);
Mean(s1);
Variance(s1);
s2 := Array([seq(GenerateFloat()^2+GenerateFloat()^2, i = 1 .. tries)]);
Mean(s2);
Variance(s2);
output is:
0.6702112097021581
0.17845439723457215
0.664707674135025
0.35463131700965245
What's wrong with it? GenerateFloat() should be as uniform as possible.

Automatic simplification is turning your,
GenerateFloat()^2+GenerateFloat()^2
into,
2*GenerateFloat()^2
before GenerateFloat() is evaluated.
One simple change to get it to work as you expected would be separate them. Eg,
restart:
with(RandomTools[MersenneTwister]):
tries := 10^4:
s := 0:
for i to tries do
t1,t2 := GenerateFloat(),GenerateFloat();
if t1^2+t2^2 < 1 then s := s+1 end if;
end do:
evalf(4*s/tries);
Another way is to use a slightly different construction which doesn't automatically simplify. Consider, single right quotes (uneval quotes) don't stop automatic simplification (which is a definition of the term if you want).
'f()^2 + f()^2';
2
2 f()
But the following does not automatically simplify,
a:=1:
'f()^2 + a*f()^2';
2 2
f() + a f()
Therefore another easy workaround is,
restart:
with(RandomTools[MersenneTwister]):
tries := 10^4:
s := 0:
a := 1;
for i to tries do
if GenerateFloat()^2 + a*GenerateFloat()^2 < 1 then s := s+1 end if;
end do:
evalf(4*s/tries);

Related

Recovering the name of a variable in Maple

I am programming a procedure in Maple. This procedure receive a list of vector fields (from the ``DifferentialGeometry'' package). I want that in the output they appear, together with the performed computations, the name of the vector fields introduced by the user.
During the procedure I refer to them by the name I have given to the parameter, but I don't actually know the "names of the variables". Is there a way to recover them? I have being looking for in the Maple documentation and in the DGinfo help, but I didn't get anything.
EXAMPLE ADDED
I have simplified the problem to the following. Consider the code:
with(DifferentialGeometry);
DGsetup([x, u], M);
X := evalDG(D_u*x+2*D_x);
myproc := proc (var)
return evalDG(var+D_u)
end proc;
myproc(X)
The output is
But I want modify the code in such a way that the output were something like
X+D_u is 2 D_x + (1+x) D_u
That is, I want to use the name ("X") of the variable in the output, not only the value (2 D_x + x D_u).
Thank you for your time.
Here is one way of handling your example.
restart;
with(DifferentialGeometry):
DGsetup([x, u], M):
myproc := proc(var::uneval) local evar;
evar := eval(var);
return evalDG(var+D_u) = evalDG(evar+D_u);
end proc:
X := evalDG(D_u*x+2*D_x):
myproc(X);
X + D_u = 2 D_u + (1 + x) D_u
Here is a variant on that idea, with two such parameters on the procedure, but also handling then in a more general manner.
restart;
with(DifferentialGeometry):
DGsetup([x, u], M):
myproc := proc(var1::uneval, var2::uneval)
local evars, res;
evars := [var1=eval(var1), var2=eval(var2)];
res := var1 + var2 + D_u;
return res = evalDG(eval(res, evars));
end proc:
X1 := evalDG(D_u*x+2*D_x):
X2 := evalDG(D_u*x+3*D_x):
myproc(X1, X2);
X1 + X2 + D_u = 5 D_x + (1 + 2 x) D_x

"var" was previously used as a variable - MatLab

I don't know why it tells me that I previously used as a variable when I have never used it before.
Here is my code:
price := 0;
temp := 0;
for i=1:m,
price += -y(i)*log( sigmoid(theta'*X(i,:)) ) -(1-y(i))*log(1-sigmoid(theta'*X(i,:)) );
end;
J = price / m;
for i=1:n,
temp := 0;
for i2=1:m,
temp += ( 1-sigmoid(theta'*X(i2,:)) - y(i2) ) * X(j,i2);
end;
grad(i) = temp;
end;
The error is here:
'price += -y(i)*log( sigmoid(theta'*X(i,:)) ) -(1-y(i))*log(1-sigmoid(theta'*X(i,:)) );'
Log error:
"price" was previously used as a variable, conflicting with its use here as the name of a function or command.
See "How MATLAB Recognizes Command Syntax" in the MATLAB documentation for details.
I guess there is nothing like += in Matlab. So, you can't do the following.
price += -y(i)*log(sigmoid(theta'*X(i,:))) - (1-y(i))*log(1-sigmoid(theta'*X(i,:)));
Rather you should do the following.
price = price + -y(i)*log(sigmoid(theta'*X(i,:))) -(1-y(i))*log(1-sigmoid(theta'*X(i,:)));
Moreover, := is not allowed according to Matlab language. Perhaps, your code is in Mupad. Check this out.

Got "Boolean" expected "LongInt" pascal

I get this error on my insertion sort algorithm:
insertionsort.lpr(19,17) Error: Incompatible types: got "Boolean" expected "LongInt"
Here's the line 19 of my code
while j > 0 and A[j]>key do
I have tried googling all over the internet but i couldn't find any syntax errors or anything.
Here's the full code if it helps :
program instert;
uses crt;
const
N = 5;
var
i:integer;
j:integer;
key:integer;
A : Array[1..N] of Integer;
procedure insertionsort;
begin
for i := 2 to N do
begin
key := A[1];
j:= i - 1;
while j > 0 and A[j]>key do
begin
A[j+1] := A[j] ;
j := j-1;
end;
A[j+1] := key ;
end;
end;
begin
A[1]:= 9;
A[2]:= 6;
A[3]:= 7;
A[4]:= 1;
A[5]:= 2;
insertionsort;
end.
I also get the same error on the bubble sort algorithm i did. Here's the error line
bubblesort.lpr(26,14) Error: Incompatible types: got "Boolean" expected "LongInt"
Here's line 26 of my algorithm:
until flag = false or N = 1 ;
Here's the full code:
program bubblesort;
uses crt;
var
flag:boolean;
count:integer;
temp:integer;
N:integer;
A : Array[1..N] of Integer;
procedure bubblesort ;
begin
Repeat
flag:=false;
for count:=1 to (N-1) do
begin
if A[count] > A[count + 1] then
begin
temp := A[count];
A[count] := A[count + 1];
A[count] := temp;
flag := true;
end;
end;
N := N - 1;
until flag = false or N = 1 ;
end;
begin
A[1]:= 9;
A[2]:= 6;
A[3]:= 7;
A[4]:= 1;
A[5]:= 2;
N := 5;
bubblesort;
end.
In Pascal, boolean operators and and or have higher precedence than the comparison operators >, =, etc. So in the expression:
while j > 0 and A[j] > key do
Given that and has higher precedence, Pascal sees this as:
while (j > (0 and A[j])) > key do
0 and A[j] are evaluated as a bitwise and (since the arguments are integers) resulting in an integer. Then the comparison, j > (0 and A[j]) is evaluated as a boolean result, leaving a check of that with > key, which is boolean > longint. You then get the error that a longint is expected instead of the boolean for the arithmetic comparison.
The way to fix it is to parenthesize:
while (j > 0) and (A[j] > key) do ...
The same issue applies with this statement:
until flag = false or N = 1 ;
which yields an error because or is higher precedence than =. So you can parenthesize:
until (flag = false) or (N = 1);
Or, more canonical for booleans:
until not flag or (N = 1); // NOTE: 'not' is higher precedence than 'or'
When in doubt about the precedence of operators, parenthesizing is a good idea, as it removes the doubt about what order operations are going to occur.

How to get/find the variable that caused Division By Zero error in delphi?

I know how to do basic exception handling. So i can raise a message on divide by zero using the 'try except' method.
What i would like to do is, find the variable that causes this error and then change its value on run time.
For Ex:
procedure Calculate();
var
a, b, c : Double;
begin
try
a := 4; //suppose i take this value from user and he enters 4
b := 0; //suppose i take this value from user and he enters 0
c := a/b;
ShowMessage(FloatToStr(c));
except
on E : EZeroDivide do
begin
ShowMessage('Exception message = '+E.Message);
//i am not sure how to identify that its variable 'b' that is causing the error and has to be changed by a default value
get(E....errorVaraiable);
E....errorVaraiable := 0.00001;
c := a/E....errorVariable;
ShowMessage(FloatToStr(c));
end;
end;
Please, can anyone help me with this?
Here's a modified version of your example that does what you want.
procedure Calculate();
var
a, b, c : Double;
begin
a := 4; //suppose i take this value from user and he enters 4
b := 0; //suppose i take this value from user and he enters 0
if IsZero(b) then
begin
ShowMessage('b cannot be 0')
end
else
begin
c := a/b;
ShowMessage(FloatToStr(c));
end;
end;

Printing symbol name and value in Mathematica

I'd like to create a function My`Print[args__] that prints the names of the symbols that I pass it, along with their values. The problem is that before the symbols are passed to My`Print, they're evaluated. So My`Print never gets to see the symbol names.
One solution is to surround every argument that I pass to My`Print with Unevaluated[], but this seems messy. Is there a way of defining a MACRO such that when I type My`Print[args__], the Mathematica Kernel sees My`Print[Unevaluated /# args__]?
You need to set the attribute HoldAll on your function, with SetAttribute[my`print].
Here's a possible implementation:
Clear[my`print]
SetAttributes[my`print, HoldAll]
my`print[args__] :=
Scan[
Function[x, Print[Unevaluated[x], " = ", x], {HoldAll}],
Hold[args]
]
I used lowercase names to avoid conflicts with built-ins or functions from packages.
EDIT:
Just to make it explicit: I have two functions here. One will print the value of a single symbol, and is implemented as a Function inside. You can just use this on its own if it's sufficient. The other is the actual my`print function. Note that both need to have the HoldAll attribute.
ClearAll[My`Print]
SetAttributes[My`Print, HoldAll]
My`Print[args___] :=
Do[
Print[
Extract[Hold[args], i, HoldForm], "=", List[args][[i]]
], {i, Length[List[args]]}
]
ape = 20;
nut := 20 ape;
mouse = cat + nut;
My`Print[ape, nut, mouse]
(* ==>
ape=20
nut=400
mouse=400+cat
*)
SetAttributes[MyPrint, HoldAll];
MyPrint[var_] :=
Module[
{varname = ToString[Hold[var]]},
Print[StringTake[varname, {6, StringLength[varname] - 1}],
" = ", Evaluate[var]]
]
Coming late to the party - one can use Listability to get a rather elegant (IMO) solution avoiding explicit loops or evaluation control constructs:
ClearAll[prn];
SetAttributes[prn, {HoldAll, Listable}];
prn[arg_] := Print[HoldForm[arg], " = ", arg];
prn[args___] := prn[{args}]
Stealing the test case from #Sjoerd,
In[21]:= prn[ape,nut,mouse]
During evaluation of In[21]:= ape = 20
During evaluation of In[21]:= nut = 400
During evaluation of In[21]:= mouse = 400+cat
Out[21]= {Null,Null,Null}
Here is another variation of My`Print to add to the mix:
ClearAll[My`Print]
SetAttributes[My`Print, HoldAll]
My`Print[expr_] := Print[HoldForm[expr], " = ", expr]
My`Print[exprs___] := Scan[My`Print, Hold[exprs]]
... and another...
ClearAll[My`Print]
SetAttributes[My`Print, HoldAll]
My`Print[args___] :=
Replace[
Unevaluated # CompoundExpression # args
, a_ :> Print[HoldForm[a], " = ", a]
, {1}
]
Either way, the use is the same:
$x = 23;
f[x_] := 1 + x
My`Print[$x, $x + 1, f[1]]
(* prints:
$x = 23
$x+1 = 24
f[1] = 2
*)
In addition to the other answers consider the functions DownValues, OwnValues and UpValues:
In[1] := f[x_] := x^2
In[2] := f[x_, y_] := (x + y)^2
In[3] := DownValues[f]
Out[3] = {HoldPattern[f[x_]] :> x^2, HoldPattern[f[x_, y_]] :> (x + y)^2}
http://reference.wolfram.com/mathematica/ref/DownValues.html