pi Approximation quiz in psyschool.com - python-3.x

I've writen this code for this quiz:
"Create a function that computes the approximation of pi, based on the number of iterations specified."
pi can be computed by 4*(1-1/3+1/5-1/7+1/9- ...).
it gives me correct answers in pycharm. but when I run it in the website it gives me wrong answers. what should I do?
thanks
def piApprox(num):
i = 1
pi = 0
while i <= num:
a = (4/((2*i)-1))*((-1)**(i-1))
pi += a
print(pi)
i += 1
return round(pi, 11)
correct answers:.................my answers:
3.13959265559...................3.0
4.0.......................................4.0
3.04183961893...................3.0
3.25236593472...................3.0

To me it looks like the round function isn't working as expected. Maybe just remove it so
return pi
and see if that makes a difference.

Related

Where is the error in Chudnovsky algorithm (python)?

I'm new to python (and coding too) so I'm following a tutorial book. I'm try to calculate pi to a set number of decimal places using the Chudnovsky algorithm from code outlined in the book; however, when I execute the code I get an error saying:
> File "C:/Users/user/Documents/Python/Scripts/Tutorials/Calculating
> pi.py", line 15, in calc
> t = (Decimal(-1)**k)*(math.factorial(Decimal(6)*k))*(13591409 + 545140134*k) TypeError: 'decimal.Decimal' object cannot be interpreted
> as an integer
Here is the original code:
from decimal import Decimal, getcontext
import math
numberofdigits = int(input("please enter the number of decimal places to calculate Pi to: "))
getcontext().prec = numberofdigits
def calc(n):
t = Decimal(0)
pi = Decimal(0)
deno = Decimal(0)
k = 0
for k in range(n):
t = (Decimal(-1)**k)*(math.factorial(Decimal(6)*k))*(13591409+545140134*k)
deno = math.factorial(3*k)*(math.factorial(k)**Decimal(3))*(640320**(3*k))
pi += Decimal(t)/Decimal(deno)
pi = pi * Decimal(12)/Decimal(640320**Decimal(1.5))
pi = 1/pi
return str(pi)
print (calc(1))
Where am I going wrong here? I have triple checked for spelling errors etc. but have not found anything but don't really understand what the decimal.decimal type error means.
EDIT:
I've been playing around with it and found that if I separate the terms of the numerator I get:
def calc(n):
t = Decimal(0)
pi = Decimal(0)
deno = Decimal(0)
k = 0 for k in range(n):
u=(Decimal(-1)**k)
x=(Decimal(6)*k)
v=math.factorial(x)
w=(13591409+545140134*k)
t = u*v*w
deno = math.factorial(3*k)*(math.factorial(k)**Decimal(3))*(640320**(3*k))
This gives me the following error:
line 17, in calc v=math.factorial(x) TypeError: 'decimal.Decimal' object cannot be interpreted as an integer
Cheers
The problem seems to be that the math.factorial() function accepts only integers or floats with integral values, but does not support Decimal objects:
print(math.factorial(6))
# 720
print(math.factorial(6.0))
# 720
print(math.factorial(Decimal(6)))
# TypeError: 'decimal.Decimal' object cannot be interpreted as an integer
Changing the value passed to math.factorial() on line 15 should fix the error:
t = (Decimal(-1)**k) * (math.factorial(6 * k)) * (13591409+545140134 * k)
Interestingly, your original code works fine using Python 3.6.9, but fails in Python 3.8.2, because this behavior was introduced in Python 3.8 (yes, this is the intended behavior).
The logic behind this behavior can be fully understood by reading this discussion about dropping support for Decimal objects in math.factorial():
Issue 33083: math.factorial accepts non-integral Decimal instances

Accuracy problems in estimating pi using Machin's method

I need to estimate pi to 100 decimal places using Machin's method which is as follows. 4(4(arctan(1/5)) - arctan(1/239)) = pi.
This formula is known to converge to pi pretty quickly, with sources citing accuracy of 72 places after the decimal in 50 iterations/terms.
I can only achieve accuracy up to 15 places after the decimal point, using Machin's formula, and I can not figure out why.
I have written a function for the Taylor series of arctan(x) and then I use that function inside another function that applies the formula I have written above. I have also tried setting higher precision using the Decimals module.
##This is the function for the taylor series of arctan(x)
def arctan(first_term, terms):
k = 0
array = []
if k < 1:
x = (((-1)**k)*(first_term)**((2*k)+1))/((2*k)+1)
k = 1
array.append(x)
if k > 0:
while k < terms:
x = x + (((-1)**k)*(first_term)**((2*k)+1))/((2*k)+1)
k += 1
array.append(x)
return array[-1]
##Here is the function for Machin's formula
def machinpi(first_term, first_term2, terms):
x = 4*(arctan(first_term, terms))-(arctan(first_term2, terms))
return x*4
Machin is famous for estimating pi to 100 decimal places by hand. I am trying to figure out how many terms of the series are required to achieve this accuracy. However, I can not find the answer if I can not first converge to 100 decimal places of pi. Using Machin's formula I expect to converge to 72 values after the decimal place in 50 iterations.
Okay I have figured this problem out. I don't know why this happens in python but calling the function I wrote like this machinpi(Decimal(1/5), Decimal(1/239), terms) is not equal to this which has the accuracy that I expect machinpi(Decimal(1)/Decimal(5), Decimal(1)/Decimal(239), terms)

Why does my if function not return the proper value?

I'm quite new at Python programming so forgive me if it seems like a stupid question. This is my code with the given results:
Code:
def Stopping_Voltage(Frequency, Phi):
x = (4.14E-15) * Frequency ##The value of (h/e) multiplied by frequency
y = Phi / (1.602E-19) ##The value of Phi/e
Energy = x * (1.602E-19)
print(Energy)
print(Phi)
print(x)
print(y)
String = 'No electron is emitted'
if Energy > Phi:
Voltage = x - y
return(Voltage)
else:
return(String)
Stopping_Voltage(10, (6.63228E-33))
Result:
6.632280000000001e-33
6.63228e-33
4.1400000000000005e-14
4.14e-14
6.310887241768095e-30
What we're asked to do is if the energy is less than or equal to phi, return the string but when testing it with the given variables, it should return the string but it is still giving me a quantitative result. I initially tried using "else" rather than "elif" but it still gave me the same thing (if that matters). When I printed the value for Energy and Phi, the energy value has a lot of zeroes after the decimal (with 1 following after all the zeroes). How do I fix this to give me the string?
Your code is fine! It does return the string, if Energy is <= Phi. It's just that your Energy in this particular example is really bigger than your Phi :) This is the scientific notation of a number, so e means 10^exponent like 2e-5 is equal to 2*10^-5. You can check it by adding print(Energy > Phi) which will print you either True or False e.g. before the if-else block.

Extremely Basic Python Program Doesn't Return Proper Value

I'm writing a very simple program that calculates how far an object has fallen due to gravity given how long it's been in the air.
(main.py)
# Importing falling_distance function
from a3_functions import falling_distance
# Doc-string
import a3_functions; print(a3_functions.falling_distance.__doc__)
# Input from user and formatted output
t = input('Enter the time (in secs): ')
print("The Object has fallen {:.2f} in {:d} seconds".format(falling_distance(t), t))
^^ Being the main module/class where the user puts in the amount of time. After that it references the program a3_functions.py which is essentially a library for various functions.
(a3_functions.py)
def falling_distance (t):
"""-------------------------------------------------------------------------
Purpose: Calculate and output falling distance (in metres) given time (in
seconds)
---------------------------------------------------------------------------
Preconditions:
t - time (int > 0)
g - gravitational constant
Postconditions:
returns:
d - distance (float > 0)
---------------------------------------------------------------------------
"""
t = int(t)
g = 9.8
d = (1/2)*g*t**2
return d
I know i can do it very simply in one program but can anyone tell me when d is being returned as 0?
In my opinion, i think it has something to do with the way eclipse is set up because it worked before. I worked on other programs, came back to this one and it broke. I feel like this is a simple problem that happens way too often and has an easy fix
You are using Python 2, not Python 3. They are often both installed on the same computer, and on most systems the default is 2 instead of 3. If you explicitly start it with python3 instead of just python, you should be able to get Python 3 if it’s installed.
Specifically, in Python 2, if you divide two integers, it converts the result to an integer, so 1/2 gives 0. This was changed to do floating-point division in Python 3.
Additionally, the input function in Python 2 is equivalent to eval(input(...)) in Python 3, so t is already an int. In Python 3, your format call doesn’t work because you can’t use {:d} on a string.

Statistical Analysis Error? python 3 proof read please

The code below generates two random integers within range specified by argv, tests if the integers match and starts again. At the end it prints some stats about the process.
I've noticed though that increasing the value of argv reduces the percentage of tested possibilities exponentially.
This seems counter intuitive to me so my question is, is this an error in the code or are the numbers real and if so then what am I not thinking about?
#!/usr/bin/python3
import sys
import random
x = int(sys.argv[1])
a = random.randint(0,x)
b = random.randint(0,x)
steps = 1
combos = x**2
while a != b:
a = random.randint(0,x)
b = random.randint(0,x)
steps += 1
percent = (steps / combos) * 100
print()
print()
print('[{} ! {}]'.format(a,b), end=' ')
print('equality!'.upper())
print('steps'.upper(), steps)
print('possble combinations = {}'.format(combos))
print('explored {}% possibilitys'.format(percent))
Thanks
EDIT
For example:
./runscrypt.py 100000
will returm me something like:
[65697 ! 65697] EQUALITY!
STEPS 115867
possble combinations = 10000000000
explored 0.00115867% possibilitys
"explored 0.00115867% possibilitys" <-- This number is too low?
This experiment is really a geometric distribution.
Ie.
Let Y be the random variable of the number of iterations before a match is seen. Then Y is geometrically distributed with parameter 1/x (the probability of generating two matching integers).
The expected value, E[Y] = 1/p where p is the mentioned probability (the proof of this can be found in the link above). So in your case the expected number of iterations is 1/(1/x) = x.
The number of combinations is x^2.
So the expected percentage of explored possibilities is really x/(x^2) = 1/x.
As x approaches infinity, this number approaches 0.
In the case of x=100000, the expected percentage of explored possibilities = 1/100000 = 0.001% which is very close to your numerical result.

Resources