I want to change this def by using lambda - python

import random
def Calculate_Pi(total):
inside = 0
for i in range(0, total):
x2 = random.random() ** 2
y2 = random.random() ** 2
if x2 + y2 <= 1.0:
inside += 1
pi = (float(inside) / total) * 4
return pi
I want to change this def by using lambda
import random as r
total = int(input("total : "))
pi = lambda inside : float(len([x for x in range(total) if r.random()**2 + r.random()**2 <= 1.0]) / total) * 4
print(pi(total))
this is my code but i don't know this is right and i want to know any better code

Not sure why you want this but you can do it this way
calculate_pi = lambda total:(sum(((random.random()**2) + (random.random()**2)) <=1.0 for _ in range(total)) / total) * 4
print(calculate_pi(5)) # 3.2

Related

McLaurin series for cosine

I want to make a cosine function that relies on the McLaurin expansion on cosine.. but it doesn't work: it should return me '-1.0..something' but it returns me another value, please can you guys help me??
code:
import math
def _cos(n:float,prec:int):
a = []
k = 0.0
for x in range(prec):
a.append(
((-1)**k)*((n**(2*k+1))/(2*k+1))
)
k+=1
z = 0
for x in a:
z+=x
return z
pi = math.pi
print(_cos(pi,200))
print(math.cos(pi))
As I can see you don't have the good formula.
((-1)**k)*((n**(2*k+1))/(2*k+1))
it's n**(2*n)
then you need to divide it by the factorial of 2n
4! = 4 * 3 * 2 * 1
2n! = 2n * 2n-1 * 2n-2 * 2n-3 ...
your formula of mac laurin is false: see maclaurin cosinus
in your loop, you do a mixture with the pow (x is the pow not k)
your correct code will be:
def _cos(n:float,prec:int):
a = []
for x in range(prec):
a.append(
((-1)**x)*((n**(2*x))/factorial(2*x))
)
z = 0
for x in a:
z+=x
return z
pi = 3.14159265359
print(_cos(pi,200))
print(math.cos(pi))
but if you do that with a precision of 200, you will be an overflow
try with 10 is already best.
i suggest you to use the precicion not from a number of iteration but from the difference between old value and new value like this :
def _cos(n:float,prec:float):
k = 0
cosine_x = 0.0
while True:
old = cosine_x + (pow(-1, k) * pow(n, 2 * k) / factorial(2 * k))
#print(old)
if 0 < abs(old - cosine_x) < prec:
return old
cosine_x = old
k += 1
pi = 3.14159265359
print(_cos(pi,0.000000000000001))
print(cos(pi))
You were not updating k, as you used x for the range and you were missing the factorial function in the division. Try with precison as 20, but 200 is too high.
Try the following code:
import math
def _cos(n:float,prec:int):
a = []
k = 0
for k in range(prec):
a.append(
((-1)**k) * ((n**(2*k))) /
math.factorial(2*k)
)
z = 0
for x in a:
z += x
return z

Trigonometric Functions: How do I write Sine and Cosine function's code without using `math` module?

I have been writing code for a module I am making for my Discord Bot. I have been trying not to use any module as it is not helping in in importing stuff. So I thought I should write the code myself for both of them.
The problem here is that I don't really know how do we make them. I couldn't find them anywhere on the net as everywhere I only saw the use of math module which I don't want to use.
I don't know how do I work with them, so I want some help.
Thank You! :)
Using Taylor expansion you get an approximation up to the desired precision.
http://hyperphysics.phy-astr.gsu.edu/hbase/tayser.html
def pow(base, exponent):
return base ** exponent
def faktorial(n):
value = float(1)
for i in range(1, n+1):
value = value * i
return value
def cos(x):
x = x * 3.14/180
value = 1
sign = -1
n = 200 # precision
i = 2
while i < n:
value = value + (pow(x, i)/faktorial(i) * sign)
i = i + 2
sign = sign * -1
return value
def sin(x):
x = x * 3.14/180
value = x
sign = -1
n = 200 # precision
i = 3
while i < n:
value = value + (pow(x, i)/faktorial(i) * sign)
i = i + 2
sign = sign * -1
return value
pi = 3.1415926535897932384626433832795028841971 # Value of constant pi
def f(n): # Factorial Function
if n == 1 or n == 0:
return 1
else:
return n * f(n - 1)
def deg(x):
rad = x * pi/180
return rad
def sin(x): # Taylor Expansion of sinx
k = 0
sinx = 0
while x >= pi:
x -= pi
if pi > x > pi / 2:
x = pi - x
while k < 15:
sinx += (-1)**k * x**(2*k + 1) / f(2*k + 1)
k += 1
return sinx
def cos(x):
cosx = sin(pi / 2 - x)
return cosx
I improved the code now. Now it gives you accurate results of up to 14 decimal places. Also instead of writing full Taylor expression formula, I used a while loop to do that. While loop here acts as a summation function of maths. I also shorten the code inside cos(x). Instead of writing Taylor's expression here, I used a conversion formula of sinx to cosx. Which reduces the calculation process. I made a little change in the code. Now you can calculate sinx of huge number too with the same accuracy.

Python Alternating + and - between fractions

I am trying to use the Nilakantha Pi Series formula and a for loop to calculate pi depending on how far into the calculation the user chooses the iterations to be. Here is the website that shows this infinite formula: https://www.mathsisfun.com/numbers/pi.html. I want to display the correct answer for iterations greater than 1, but only the first iteration shows the correct answer. Here is what I have so far:
def for_loop(number):
n = 4
pi = 3
for i in range(1, number + 1):
den = (n-2) * (n-1) * n
if (number % 2 == 0):
pi -= (4 / den)
print(pi)
else:
pi += (4 / den)
print(pi)
n = n + 2
The immediate problem is that you are checking if number, not i, is even or odd. But you don't need any such checks. You just have to alternate the numerator between 4 and -4.
def for_loop(number):
n = 4
pi = 3
num = 4
for _ in range(number):
den = (n-2) * (n-1) * n
pi += num/den
print(pi)
num *= -1
n += 2
or
from itertools import cycle
def for_loop(number):
n = 4
pi = 3
for num in cycle([4, -4]):
den = (n-2)*(n-1)*n
pi += num/den
print(pi)
n += 2
or even
from itertools import cycle, count
def for_loop(number):
pi = 3
for num, n in zip(cycle([4,-4]), count(4, 2)):
den = (n-2)*(n-1)*n
pi += num/den
print(pi)
You have to rework the condition of %2
def for_loop(number):
n = 4
pi = 3
for i in range(1, number + 1):
den = (n-2) * (n-1) * n
if (i % 2 == 0):# replace number by i , its alternating between even/uneven, however number is all the time the same.
pi -= (4 / den)
else:
pi += (4 / den)
print(pi)
n = n + 2
This is another way of doing it by using the reduce() function of the functools module, to solve the operation in the denominator of the fraction. To change the sign (-1 or 1) for each iteration, you can just multiply it by -1.
from functools import reduce
def nilakantha(n):
i, sign, start, base, stop = 1, 1, 2, 3, 4
res = base
while i < n and n > 1:
res += sign * (4 / reduce(lambda x, y: x * y, range(start, stop + 1)))
sign *= -1
start = stop
stop = start + 2
i += 1
return res
Example output
>>> nilakantha(524)
3.141592655327371

writing multiple data calculated from a function in the same file

I am trying to write a data calculated from this function in a file. But the function is called number of times. Say there are 9 numbers in another file and this function will calculate the root for each of those 9 numbers. These 9 roots from this function should be written in the same file. But the way I have done it here will write calculated root in the file but the next one will replace this in the file. There are other mathematical functions that are carried out for each of those 9 numbers before this function is called therefore the functions are called again and again separately.Is it possible to write them all in the same file? Thank you.
def Newton(poly, start):
""" Newton's method for finding the roots of a polynomial."""
x = start
poly_diff = poly_differentiate(poly)
n = 1
counter = 0
r_i = 0
cFile = open("curve.dat", "w")
while True:
if (n >= 0) and (n < 1):
break
x_n = x - (float(poly_substitute(poly, x)) / poly_substitute(poly_diff, x))
if x_n == x:
break
x = x_n # this is the u value corresponding to the given time
n -= 1
counter += 1
x = str(x)
cFile.write('\n' + x + '\n')
if r_i:
print "t(u) = ", (x, counter)
else:
print "t(u) = ", x
cFile.close
After following the suggestions I got I changed the code to the following:
def Newton(poly, start):
""" Newton's method for finding the roots of a polynomial."""
x = start
poly_diff = poly_differentiate(poly)
n = 1
counter = 0
while True:
if (n >= 0) and (n < 1):
break
x_n = x - (float(poly_substitute(poly, x)) / poly_substitute(poly_diff, x))
if x_n == x:
break
x = x_n # this is the u value corresponding to the given time
n -= 1
counter += 1
yield x
Bezier(x)
def Bezier(u_value) :
""" Calculating sampling points using rational bezier curve equation"""
u = u_value
p_u = math.pow(1 - u, 3) * 0.7 + 3 * u * math.pow(1 - u, 2) * 0.23 \
+ 3 * (1 - u) * math.pow(u, 2) * 0.1 + math.pow(u, 3) * 0.52
p_u = p_u * w
d = math.pow(1 - u, 3) * w + 3 * u * w * math.pow(1 - u, 2) + 3 * (1 - u) *\
w * math.pow(u, 2) + math.pow(u, 3) * w
p_u = p_u / d
yield p_u
plist = list (p_u)
print plist
I followed the same thing in the Bezier() function but plist is not created as it doesn't print anything. Please help. Thank you.
Your function does two things: It calculates the roots of a polynomial, and it writes the result to an output file. Functions should ideally do one thing.
So, try breaking this up into a function that receives a polynomial and returns a list containing the roots, and then just write that list to a file in one step.
The simplest way to modify your function would be to replace the lines
x = str(x)
cFile.write('\n' + x + '\n')
with
yield x
Then you can call your function like this:
roots = list(Newton(polynomial, start))
To understand this, read about generators. To write the resulting list to a file, you can use this code:
with open("curve.dat", "w") as output_file:
output_file.write("\n".join(str(x) for x in roots)
While I'm not completely understanding what you are asking I think the answer can be boiled down to:
Open the file in append mode, not in write mode. So instead of
cFile = open("curve.dat", "w")
do
cFile = open("curve.dat", "a")
why use yield in Bezier, it doesn't return multiple values, so you can change:
yield p_u
plist = list (p_u)
print plist
to:
print list(p_u)
return p_u

passing a value calculated from one function to another

I have been doing python programming for my project and I have just started. This might be another trivial question. I have this code in which I need to use a value calculated in the function poly_root() which is x. That value should be used as u in the bezier() function. After poly_root() function it should go to bezier() function with its calculated value. I dont know if I am doing it in the correct way. There is no error but it doesnt print t from the bezier() function. Thank you very much.
import copy
import math
poly = [[-0.8,3], [0.75,2], [-0.75,1], [0.1,0]]
def poly_diff(poly):
""" Differentiate a polynomial. """
newlist = copy.deepcopy(poly)
for term in newlist:
term[0] *= term[1]
term[1] -= 1
return newlist
def poly_apply(poly, x):
""" Apply values to the polynomial. """
sum = 0.0 # force float
for term in poly:
sum += term[0] * (x ** term[1])
return sum
def poly_root(poly, start, n, r_i):
""" Returns a root of the polynomial, with a starting value."""
poly_d = poly_diff(poly)
x = start # starting guess value
counter = 0
while True:
if (n >= 0) and (n < 1):
break
x_n = x - (float(poly_apply(poly, x)) / poly_apply(poly_d, x))
if x_n == x:
break
x = x_n # this is the u value corresponding to the given time which will be used in bezier equation
n -= 1
counter += 1
if r_i:
#print [x, counter])
return [x, counter]
else:
#print x
return x
bezier(x)
def bezier(value) :
""" Calculates control points using rational bezier curve equation"""
u = value
w = 5
t = math.pow(1-u,3) * points[0][0] + 3 * u * math.pow(1-u,2) * points[1][0] \
+ 3 * (1-u) * math.pow(u,2) * points[2][0] + math.pow(u,3) * points[3][0]
t = t * w
d = math.pow(1-u,3) * w + 3 * u * w * math.pow(1-u,2) + 3 * (1-u) * w \
* math.pow(u,2) + math.pow(u,3) * w
t = t / d
print t
if __name__ == "__main__" :
poly_root(poly, 0.42, 1, 0)
In this part of code:
if r_i:
#print [x, counter])
return [x, counter]
else:
#print x
return x
bezier(x)
bezier(x) is unreachable. You need to rewrite it.
It would be better for poly_root to return the same type of thing in both situations (i.e. a list with two elements) ...
if r_i:
return [x, counter]
else:
return [x, None]
Then at the bottom, you can have ...
if __name__ == "__main__" :
x, counter = poly_root(poly, 0.42, 1, 0)
if counter is None: # I don't know if this is what you intended with your code.
bezier(x)

Categories