Using python 3: I have three functions: montePi, isInCircle and main.
I need to have the isInCircle called by montePi. The function will work, it just says that isInCircle is not defined. How can I define it?
import random
import math
def montePi(numDarts):
inCircle = 0
def isInCircle(x, y, r):
r = 1
d = math.sqrt(x**2 + y**2)
if d <= r:
return True
else:
return False
for i in range(numDarts):
x = random.random()
y = random.random()
d = math.sqrt(x**2 + y**2)
if d <= 1:
inCircle = inCircle +1
pi = inCircle / numDarts * 4
return pi
def main():
print(montePi(100))
print(montePi(1000))
print(montePi(10000))
print(montePi(100000))
main()
Because function isInCircle is defined in montePi, it can be called within montePi but not other functions as it is local. If you define isInCircle outside of montePi then you'll be able to call it from main.
Not sure what you're trying to program here, but there seems to be a chance that this question, regarding functions within functions can help you decide what you want here. Here is a question that covers how scopes work.
Should you need to call isInCircle from main or outside main, then this is how it should be formatted;
import random
import math
def isInCircle(x, y, r):
r = 1
d = math.sqrt(x**2 + y**2)
if d <= r:
return True
else:
return False
def montePi(numDarts):
inCircle = 0
for i in range(numDarts):
x = random.random()
y = random.random()
d = math.sqrt(x**2 + y**2)
if d <= 1:
inCircle = inCircle +1
pi = inCircle / numDarts * 4
return pi
def main():
print(montePi(100))
print(montePi(1000))
print(montePi(10000))
print(montePi(100000))
main()
Related
So far, finding the hypotenuse, "side c" works fine without problems, the problem is when I try to calculate the angle, I am pretty sure it's returning a wrong value for the angle.
import math
from math import sqrt
class Triangle:
def __init__(self, side_a, side_b, ):
self.side_a = side_a
self.side_b = side_b
def SidesCalculate(self, ):
side_c = sqrt(self.side_a ** 2 + self.side_b ** 2)
return side_c
def AnglesCalculate(self, side_c):
x = math.sin(self.side_a / side_c)
math.asin(x)
x = round(x * 180 / math.pi)
return x
g = Triangle(side_a=int(input("Enter side a: ")), side_b=int(input("Enter side b: ")))
print("side c =", + g.SidesCalculate())
print("angle is =", + g.AnglesCalculate(side_c=True), '°')
Here is a way to do what you want.
First when you compute side_c, save it as an attribute.
def SidesCalculate(self, ):
self.side_c = sqrt(self.side_a ** 2 + self.side_b ** 2)
return self.side_c
Secondly, give the parameter side_c a default value None. (You also have another math error in the following function pointed by CFLS)
def AnglesCalculate(self, side_c = None):
if side_c == None:
side_c = self.side_c
x = math.asin(self.side_a / side_c)
x = round(x * 180 / math.pi)
return x
Now, if you want the class to pick previously computed side_c, you can do this:
g = Triangle(side_a=int(input("Enter side a: ")), side_b=int(input("Enter side b: ")))
print("side c =", + g.SidesCalculate())
print("angle is =", + g.AnglesCalculate(), '°')
def AnglesCalculate(self, side_c):
x = math.asin(self.side_a / side_c)
x = round(x * 180 / math.pi)
return x
I need to both calculate and plot the integral below in Python:
integral of the function e^(-t^2) from x=0 to x=3
So far I've managed to calculate the integral using Simpson's rule. The next bit which I'm struggling with is plotting the integral of e^(-t^2) vs x from x=0 to x=3 (see the image above).
Here's the code I've written to calculate the integral -
from math import exp
def f(t):
return exp(-(t**2))
a = 0
b = 3
h = 0.1
N = int((b-a)/h)
s_even = 0
s_odd = 0
for k in range(1,N,2):
s_odd += f(a+k*h)
for k in range(2,N,2):
s_even += f(a+k*h)
s = f(a) + f(b) + 4*s_odd + 2*s_even
Integral = h*s/3
print(Integral)
How do I then create a graph of this integral?
Here's a script I wrote that performs your calculation and plots it using PyQtGraph:
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
from math import exp
class I:
def f(self,t):
return exp(-(t**2))
def __init__(self, a = 0, b = 3, h = 0.1):
N = int((b-a)/h)
s_even = s_odd = 0
for k in range(1,N,2):
s_odd += self.f(a+k*h)
for k in range(2,N,2):
s_even += self.f(a+k*h)
s = self.f(a) + self.f(b) + 4*s_odd + 2*s_even
self.I = h*s/3
def __str__(self):
return "I: %s" % self.I
def plot(array):
app = QtGui.QApplication([])
win = pg.GraphicsWindow(title="Basic plotting examples")
win.resize(1000,600)
win.setWindowTitle('pyqtgraph example: Plotting')
# Enable antialiasing for prettier plots
pg.setConfigOptions(antialias=True)
p1 = win.addPlot(title="Basic array plotting", y=array)
QtGui.QApplication.instance().exec_()
def main():
a=0
b=a+0.001
points=[]
while(a<3):
points.append(I(a,b).I)
a=b
b=a+0.001
plot(points)
## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
main()
Here is the graph it draws:
Thanks for your help Red Cricket. It looks like you may have graphed the function e^(-t^2) rather than the integral of that function. Nonetheless, I think I've worked it out; I've discovered scipy has an integrate function:
from math import exp
from numpy import arange
from scipy import integrate
def f(t):
return exp(-(t**2))
a = 0
b = 3
h = 0.1
N = int((b-a)/h)
s_even = 0
s_odd = 0
for k in range(1,N,2):
s_odd += f(a+k*h)
for k in range(2,N,2):
s_even += f(a+k*h)
s = f(a) + f(b) + 4*s_odd + 2*s_even
I = h*s/3
function = []
x = []
for t in arange(0,4,h):
function.append(f(t))
for i in arange(0,4,h):
x.append(i)
function_int = integrate.cumtrapz(function,x,initial=0)
plot(x,function_int)
show()
print(I)
This produces a graph of the integral and prints the final value of the integral itself. Hooray!
I'm trying to implement ECDSA using python as part of my homework, I have a function named multiplication which takes two arguments Point P and t calculates B= tP.I have implemented this algorith based on iterative double and add algorithm on this wikipedia page the problem is when p coordination is small(one or two digits), the algorithm works fine but when coordination is large (about 70 digits) the result is different than what it supposed to be. here is the part of my code which calculates multiplication:
def addition(self, p, q):
if p.is_infinite:
return q
elif q.is_infinite:
return p
else :
if (q.x - p.x) == 0:
point = Point.Point(0, 0)
point.is_infinite = True
return point
s = int(((q.y - p.y) * Utils.Utils.mode_inverse(q.x - p.x, self.prime)) % self.prime)
xr = int((math.pow(s, 2) - p.x - q.x) % self.prime)
yr = int(((s * (p.x - xr)) - p.y) % self.prime)
r = Point.Point(xr, yr)
return r
def double(self, p):
if p.is_infinite:
return p
if p.y == 0:
point = Point.Point(0, 0)
point.is_infinite = True
return point
s = int((((3 * math.pow(p.x, 2)) + self.a) * Utils.Utils.mode_inverse(2 * p.y, self.prime)) % self.prime)
xr = int((math.pow(s, 2) - p.x - p.x) % self.prime)
yr = int(((s * (p.x - xr)) - p.y) % self.prime)
r = Point.Point(xr, yr)
return r
def multiplication(self, p, t):
bin_t = bin(t)[2:]
Q = Point.Point(p.x, p.y)
Q.is_infinite = True
for i, digit in enumerate(bin_t):
Q = self.double(Q)
if digit == '1':
Q = self.addition(Q, p)
return Q
Here is my Util class:
class Utils(object):
#staticmethod
def mode_inverse(a, m):
return pow(a, m - 2, m)
Here is my Point class:
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
self.is_infinite = False
I use Curve P-224 parameters which are:
p = 26959946667150639794667015087019630673557916260026308143510066298881
a = -3
b = 18958286285566608000408668544493926415504680968679321075787234672564
Gx = 19277929113566293071110308034699488026831934219452440156649784352033
Gy = 19926808758034470970197974370888749184205991990603949537637343198772
according to calculator http://www.christelbach.com/eccalculator.aspx I should get this result for calculating 2G:
Px = 11838696407187388799350957250141035264678915751356546206913969278886
Py = 2966624012289393637077209076615926844583158638456025172915528198331
but what I actually get is:
Px = 15364035107168693070617763393106849380516103015030577748254379737088
Py = 7033137909116168824469040716130881489351924269422358605872723100109
Is there any way to fix this?
This was just a guess:
math.pow returns a floating point number (which has finite precision). I'd suggest using e.g. s.x * s.x instead of math.pow(s.x,2) in case the issue is hitting precision issues with bigger numbers.
In the code below, I have two functions: func1 and gillespie. I have defined p_tot_stoch as a global variable, within func1. (The reason for placing it inside a function is to allow Numba's #jit wrapper to work properly... Numba is used for code optimization.)
But when I try to print p_tot_stoch at the very end of the code, I get the following error message:
Traceback (most recent call last):
File "C:/Users/dis_YO_boi/Documents/Programming/Python/CodeReview.py", line 85, in <module>
p_tot_stoch = gillespie()
NameError: global name 'p_tot_stoch' is not defined
I declared it as global, but it looks like the main function gillespie cannot access it. How can I fix this?
My code is below, thanks for any help.
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from numba import jit
import math
random = np.random
DELTA = 1e-3
SIM_NUM = 100
K_MINUS = 1e-3
K_CAT = 1 - 1e-3
ZETA = 1e-4
D = 10000
QP_VEC = np.logspace(-2, 1, 101, 10)
KAPPA_M = (K_CAT + K_MINUS) / ZETA
P0_VEC = QP_VEC / DELTA
QP_DEG = np.true_divide(1000*D*QP_VEC*K_CAT,1000*QP_VEC+KAPPA_M)
#jit
def func1():
global p_tot_stoch
p_tot_stoch = np.empty((SIM_NUM, len(QP_VEC)))
#jit
def gillespie(max_time=1000):
for len_qp_ind in range(len(QP_VEC)):
qp = QP_VEC[len_qp_ind]
p0 = math.ceil(P0_VEC[len_qp_ind])
for sim_num_ind in range(SIM_NUM):
p = p0
d = D
dp = time = 0
while True:
tot = [qp, ZETA * p * d, K_MINUS * dp, K_CAT * dp]
for i in range(3):
tot[i + 1] += tot[i]
p_tot = p + dp
kt = tot[-1]
time += -np.log(1 - random.random()) / kt
if time > max_time:
p_tot_stoch[sim_num_ind, len_qp_ind] = p_tot
break
event_kt = random.random() * kt
if event_kt < tot[0]:
p += 1
elif event_kt < tot[1]:
p -= 1
dp += 1
d -= 1
elif event_kt < tot[2]:
p += 1
dp -= 1
d += 1
elif event_kt < tot[3]:
dp -= 1
d += 1
return p_tot_stoch
if __name__ == '__main__':
p_tot_stoch = gillespie()
p_mean = p_tot_stoch.mean(axis=0)
p_std = p_tot_stoch.std(axis=0)
print(p_tot_stoch)
cat test.py
my_variable = 0
def func1():
global my_variable
my_variable = -1
print "func1:{0}".format(my_variable)
def gillespie():
global my_variable
my_variable = 4
print "gillespie:{0}".format(my_variable)
# Starts testing...
print "before:{0}".format(my_variable)
func1()
gillespie()
print "after:{0}".format(my_variable)
python test.py
before:0
func1:-1
gillespie:4
after:4
You can declare your variable p_tot_stoch(in my test.py I declared a variable named my_varialble it is used in func1() and gillespie()) on the top of your script and outside of your functions. Each time you want to modify it you have to declare it is a global variable and then assign a new value to it.
Im using python2.7
I modified #haifzhan's example because it is simple. Python benefits from OOP tremendously and it is a sin not to use it:
#!/usr/bin/env python3
class Stoch:
def __init__(self):
self.my_variable = 0
def __str__(self):
return str(self.my_variable)
def func1(self):
self.my_variable = -1
print ("func1:", self)
def gillespie(self):
self.my_variable = 4
print ("gillespie:", self)
#classmethod
def main(cls):
stoch = Stoch()
print ("before:", stoch)
stoch.func1()
stoch.gillespie()
print ("after:", stoch)
if __name__ == '__main__':
Stoch.main()
I'm currently writing a code to perform Gaussian elimination in MATLAB and then write out the code needed to generate a LaTex file showing all the steps. A lot of the times when I do Gaussian elimination the answers start turning into Fractions. So I thought as a nice learning exercise for classes in Matlab that I would write a Fraction class. But I have no clue how to overload operators and frankly Mathwork's documentation wasn't helpful.
classdef Fraction
properties
numer
denom
end
methods
function a = Fraction(numer,denom)
a.denom = denom;
a.numer = numer;
end
function r = mtimes(a,b)
r = Fraction(a.numer*b.numer,a.denom*b.demon);
end
function r = plus(a,b)
c = a.numer*b.denom+a.denom*b.numer;
d = a.denom*b.denom;
r = Fraction(c,d);
function r = minus(a,b)
c = a.numer*b.denom-a.denom*b.numer;
d = a.denom*b.denom;
r = Fraction(c,d);
end
function r = mrdivide(a,b)
r = Fraction(a.numer*b.denom,a.denom*b.numer);
end
function b = reduceFrac(a)
x = a.numer;
y = b.denom;
while y ~= 0
x = y;
y = mod(x,y);
end
b =Fraction(a.numer/x, a.denom/x)
end
end
end
The plus operator works but the other three do not. Does any one have any ideas? Also how do I call my method reduceFrac?
Fraction.reduceFrac(Fraction(2.4))
I thought that the code above would work, but it didn't. Below is the python version of what I am trying to acheive.
Fraction.py
class Fraction(object):
"""Fraction class
Attributes:
numer: the numerator of the fraction.
denom: the denominator of the fraction.
"""
def __init__(self, numer, denom):
"""Initializes the Fraction class
Sets the inital numer and denom for the
fraction class.
Args:
numer: Top number of the Fraction
denom: Bottom number of the Fraction
Returns:
None
Raises:
None
"""
self.numer = numer
self.denom = denom
def __str__(self):
"""function call along with the print command
Args:
None
Returns:
String: numer / denom.
Raises:
None
"""
return str(self.numer) + '/' + str(self.denom)
def get_numer(self):
return self.numer
def set_numer(self, numer):
self.numer = numer
def get_denom(self):
return self.denom
def set_denom(self, denom):
self.denom = denom
def __add__(self, other):
numer = self.numer*other.denom+other.numer*self.denom
denom = self.denom*other.denom
return Fraction.reduceFrac(Fraction(numer,denom))
def __div__(self, other):
numer = self.numer*other.denom
denom = self.denom*other.numer
return Fraction.reduceFrac(Fraction(numer,denom))
def __sub__(self, other):
numer = self.numer*other.denom-other.numer*self.denom
denom = self.denom*other.denom
return Fraction.reduceFrac(Fraction(numer,denom))
def __mul__(self, other):
numer = self.numer*other.numer
denom = self.denom*other.denom
return Fraction.reduceFrac(Fraction(numer,denom))
def reduceFrac(self):
x = self.numer
y = self.denom
while y != 0:
(x, y) = (y, x % y)
return Fraction(self.numer/x, self.denom/x)
if __name__ == "__main__":
v = Fraction(4,3)
g = Fraction(7,8)
r = Fraction(4,8)
a = v + g
print a
s = v - g
print s
d = v / g
print d
m = v * g
print m
f = Fraction.reduceFrac(r)
print f
Your plus function misses an end