Calling a function multiple times with return value - function

from graphics import *
def draw():
returnStuff = {'again' : 0, '1st' : 1 }
draw.again = False
win = GraphWin("Quadrilateral Maker", 600, 600)
win.setBackground("yellow")
text = Text(Point(150, 15), 'Click 4 points to create a Quadrilateral')
text.draw(win)
#gets the 4 points
p1 = win.getMouse()
p1.draw(win)
p2 = win.getMouse()
p2.draw(win)
p3 = win.getMouse()
p3.draw(win)
p4 = win.getMouse()
p4.draw(win)
vertices = [p1, p2, p3, p4]
#draws the shape
quad = Polygon(vertices)
quad.setFill('red')
quad.setOutline('black')
quad.setWidth(3)
quad.draw(win)
text.setText('Click in the appropriate box.')
#Quit box
quitBox = Rectangle(Point(30, 500), Point(100,550))
quitBox.setFill('green')
quitBox.draw(win)
quitorNah = Text(Point(60, 490), 'Quit')
quitorNah.draw(win)
#again box
quitBox = Rectangle(Point(480, 500), Point(550,550))
quitBox.setFill('green')
quitBox.draw(win)
quitorNah = Text(Point(510, 490), 'Draw Again')
quitorNah.draw(win)
click = win.getMouse()
x = click.getX()
y = click.getY()
while True:
if 30 < x < 100 and 500 < y < 550:
returnStuff['again'] = 0
win.close()
break
elif 480 < x < 550 and 500 < y < 550:
returnStuff['again'] = 1
win.close()
break
return returnStuff
count = 1
returnValue = draw()
if returnValue['1st'] == 1:
count = 0
while count == 1 or returnValue['again'] == 1:
return_value = draw()
So I have this simple interactive program using Zelle graphics, it asks the user to click on 4 points in a window and from that it creates a shape. Then, the user is shown 2 boxes, one to quit and one to draw again. My draw again isn't working, and it has something to do with the return value. I am returning a dictionary, as I need access to 2 of the variables within the function. In the 'returnStuff' dictionary, I have a part called 'again', which is initially set to 0. If the user clicks in the run again box, it changes this value to 1, and then outside the function I have an if statement that should call the function again if that again value is 1. It does this properly the FIRST time, but the 2nd time around my program just stops all together, and I don't understand why.
Can anybody explain why this is happening?

I think you need a while...
while count==1 or returnValue['again'] == 1:
returnValue = draw()

Related

How to change marker style in polar plot with octave?

I am trying to change the appearance of the markers in a polar plot in octave.
r = rand(1,10); % the radius
t = 30*rand(1,10); % the angles
polar(t,r,'o') % the plot
It seems we can only change the shape, by replacing 'o' by 's' or whatever.
However, I didn't find a way to change the size and the colors of the markers.
Does anyone have an idea?
Thanks in advance.
Best,
It is possible through the polar handle:
h = polar(t,r,'o')
% list all graphical properties for this object
get(h)
set(h,'marker','v', 'markerfacecolor','g', 'markersize',10)
yields
>> h = polar(t,r,'o') % the plot
h = -64.073
>> get(h)
ans =
scalar structure containing the fields:
beingdeleted = off
busyaction = queue
buttondownfcn = [](0x0)
children = [](0x1)
clipping = on
createfcn = [](0x0)
deletefcn = [](0x0)
handlevisibility = on
hittest = on
interruptible = on
parent = -69.944
pickableparts = visible
selected = off
selectionhighlight = on
tag =
type = line
uicontextmenu = [](0x0)
userdata = [](0x0)
visible = on
color =
0 0.4470 0.7410
displayname =
linejoin = round
linestyle = none
linewidth = 0.5000
marker = o
markeredgecolor = auto
markerfacecolor = none
markersize = 6
xdata =
Columns 1 through 6:
0.978470 -0.060967 -0.436276 -0.268739 0.441890 -0.586862
Column 7 through 10:
0.746687 -0.063825 0.368511 0.271495
xdatasource =
ydata =
Columns 1 through 6:
0.049178 -0.426698 0.380388 -0.101611 -0.699609 -0.266804
Column 7 through 10:
0.383766 -0.903458 0.764035 -0.126044
ydatasource =
zdata = [](0x0)
zdatasource =
>> set(h,'marker','v', 'markerfacecolor','g', 'markersize',10)

How to plot Iterations in Julia

I coded a function picircle() that estimates pi.
Now I would like to plot this function for N values.
function Plotpi()
p = 100 # precision of π
N = 5
for i in 1:N
picircle(p)
end
end
3.2238805970149254
3.044776119402985
3.1641791044776117
3.1243781094527363
3.084577114427861
Now I am not sure how to plot the function, I tried plot(PP()) but it didn't work
Here I defined picircle:
function picircle(n)
n = n
L = 2n+1
x = range(-1, 1, length=L)
y = rand(L)
center = (0,0)
radius = 1
n_in_circle = 0
for i in 1:L
if norm((x[i], y[i]) .- center) < radius
n_in_circle += 1
end
end
println(4 * n_in_circle / L)
end
Your problem is that your functions don't actually return anything:
julia> x = Plotpi()
3.263681592039801
3.0646766169154227
2.845771144278607
3.18407960199005
3.044776119402985
julia> x
julia> typeof(x)
Nothing
The numbers you see are just printed to the REPL, and print doesn't return any value:
julia> x = print(5)
5
julia> typeof(x)
Nothing
So you probably just want to change your function so that it returns what you want to plot:
julia> function picircle(n)
n = n
L = 2n+1
x = range(-1, 1, length=L)
y = rand(L)
center = (0,0)
radius = 1
n_in_circle = 0
for i in 1:L
if norm((x[i], y[i]) .- center) < radius
n_in_circle += 1
end
end
4 * n_in_circle / L
end
Then:
julia> x = picircle(100)
3.263681592039801
julia> x
3.263681592039801
So now the value of the function is actually returned (rather than just printed to the console). You don't really need a separate function if you just want to do this multiple times and plot the results, a comprehension will do. Here's an example comparing the variability of the estimate with 100 draws vs 50 draws:
julia> using Plots
julia> histogram([picircle(100) for _ ∈ 1:1_000], label = "100 draws", alpha = 0.5)
julia> histogram!([picircle(20) for _ ∈ 1:1_000], label = "20 draws", alpha = 0.5)

Implementing Laguerre's root finding method

I'm trying to implement robust / stable Laguerre's method. My code works for most of polynomials but for few it "fails". Respectively I don't know how to properly handle "corner" cases.
Following code tries to find single root (F64 - 64bit float, C64 - 64bit complex):
private static C64 GetSingle( C64 guess, int degree, C64 [] coeffs )
{
var i = 0;
var x = guess;
var n = (F64) degree;
while( true )
{
++Iters;
var v0 = PolyUtils.Evaluate( x, coeffs, degree );
if( v0.Abs() <= ACCURACY )
break;
var v1 = PolyUtils.EvaluateDeriv1( x, coeffs, degree );
var v2 = PolyUtils.EvaluateDeriv2( x, coeffs, degree );
var g = v1 / v0;
var gg = g * g;
var h = gg - ( v2 / v0 );
var f = C64.Sqrt(( n - 1.0 ) * ( n * h - gg ));
var d0 = g - f;
var d1 = g + f;
var dx = d0.Abs() >= d1.Abs() ? ( n / d0 ) : ( n / d1 );
x -= dx;
// if( dx.Abs() <= ACCURACY )
// break;
if( ++i == ITERS_PER_ROOT ) // even after trying all guesses we didn't converted to the root (within given accuracy)
break;
if(( i & ( ITERS_PER_GUESS - 1 )) == 0 ) // didn't converge yet --> restart with different guess
{
x = GUESSES[ i / ITERS_PER_GUESS ];
}
}
return x;
}
At the end if it didn't found root it tries different guess, first quess (if not specified) is always 'zero'.
For example for 'x^4 + x^3 + x + 1' it founds 1st root '-1'.
Deflates (divides) original poly by 'x + 1' so 2nd root search continues with polynomial 'x^3 + 1'.
Again it starts with 'zero' as initial guess... but now both 1st and 2nd derivates are 'zero' which leads to 'zero' in 'd0' and 'd1'... ending by division-by-zero (and NaNs in root).
Another such example is 'x^5 - 1' - while searching for 1st root we again ends with zero derivates.
Can someone tell me how to handle such situations?
Should I just try another guess if derivates are 'zero'? I saw many implementation on net but none
had such conditions so I don't know if I'm missing something.
Thank you

Piecewise Functions in R

I'm trying to plot a piecewise function in R that is equal to -3 if x < 0, 1/3 * x^3 if x is between 0 and 5 (inclusive), and 4x otherwise. The function I've been running seems to work, but the plot returns an error message. The code I wrote is:
g <- function(x) {
if (x < 0)
-3 # first component
else if (x >= 0 & x <= 5)
(1/3) * x #second component
else
4*x # third component
}
Then when I try to plot it with
plot(g, -20, 20)
I get
Error in curve(expr = x, from = from, to = to, xlim = xlim, ylab = ylab, :
'expr' did not evaluate to an object of length 'n'
In addition: Warning message:
In if (x < 0) -3 else if (x >= 0 & x <= 5) (1/3) * x else 4 * x :
the condition has length > 1 and only the first element will be used
I can't quite figure out how to troubleshoot this, and the 'ifelse' function returned a dark black line when I attempted to plot it, which I'd prefer to avoid, so this seems to be my best bet.
I would greatly appreciate any insights.

Spawn Function in Corona SDK

Okay so I kind of am almost there but need a little push:
My dustbins spawn but there are a few to begin with like I want and then after about 30 seconds of the numbers of dustbins increasing there are 1000's all clumped together.. What can i do to alter my function so that its only ever a few at a time:
function spawnDustbin()
dustbin = {}
for i = 1,800 do
dustbin[i] = display.newImage("dustbin.png")
dustbin[i].xScale = 0.55
dustbin[i].yScale = 0.55
dustbin[i].y = 555
dustbin[i].x = (math.random(1000,1500) * i)
dustbin[i].speed = 4
physics.addBody( dustbin[i], "static", { friction=1.0, density=1.0, bounce=0, radius=30,} )
dustbin[i].enterFrame = moveDustbin
Runtime:addEventListener("enterFrame", dustbin[i])
end
end
and the movedustbin function simply moves the dustbin in the negative x direction:
function moveDustbin(self,event)
if self.x < -2560 then
self.x = 2560
else
self.x = self.x - val
end
end
First 20ish seconds:
http://i.stack.imgur.com/7iEeP.png
After 20 seconds:
http://i.stack.imgur.com/aae0D.png
Thank you very much
James
That "spawnDustbin" function above is spawning 800 dustbins every frame. That will really crush your performance, and I am pretty certain you don't want to create that many objects every frame.
You might want to do something like this:
local dustbin = {}
local i = 0
local function spawnDustbin()
i = i+1
dustbin[i] = display.newImage("dustbin.png")
dustbin[i].xScale = 0.55
dustbin[i].yScale = 0.55
dustbin[i].y = 555
dustbin[i].x = (math.random(1000,1500) * i)
dustbin[i].speed = 4
physics.addBody( dustbin[i], "static", { friction=1.0, density=1.0, bounce=0, radius=30,} )
dustbin[i].enterFrame = moveDustbin
Runtime:addEventListener("enterFrame", dustbin[i])
end
timer.performWithDelay(500, spawnDustbin, 10)
YMMV but that will spawn 10 dustbins in 5 seconds.