i am very new to python and am trying to run some code for class, however I am coming into a weird error note I just put in a random value for n and k to see if the code would work
$python main.py
Traceback (most recent call last):
File "main.py", line 10, in <module>
while(k):
NameError: name 'k' is not defined
here is my code, I have defined n and n works with no problem, but k seems to be an issue
def binary(n,k):
n = 6
k = 1.5
#'n' is the fractional number
#'k' is the number of bits up to the loop ;
integral = int(n)
fraction = n-integral
b = '.'
while(k):
fraction = fraction * 2
fra_num = int(fraction)
if (frac_num == 1):
fraction = fraction - frac_num
b = b + '1'
else:
b = b + '0'
k = k - 1
print b
As commented, your biggest problem here is your indentation. Your while loop is not inside your function. Try this for indentation:
def binary(n,k):
n = 6
k = 1.5
#'n' is the fractional number
#'k' is the number of bits up to the loop ;
integral = int(n)
fraction = n-integral
b = '.'
while(k):
fraction = fraction * 2
fra_num = int(fraction)
if (frac_num == 1):
fraction = fraction - frac_num
b = b + '1'
else:
b = b + '0'
k = k - 1
print b
Related
I am trying to code the Chudnovsky algorithm in python. However, when I run my code, it gives me a very small number (-5.051212624421025e-55) which is not pi. I am in middle school, and I don't know anybody that can help me. What am I doing wrong?
Here is a link to the Chudnovsky formula: https://levelup.gitconnected.com/generating-the-value-of-pi-to-a-known-number-of-decimals-places-in-python-e93986bb474d
Here is my code:
import math
def fact(exi):
memory = exi
for i in range(1, exi):
memory *= i
return memory
k = 10
s = 0
for i in range(0, k):
a = -1^k
b = fact(6*k)
c = (545140134*k) + 13591409
d = fact(3*k)
e = (fact(k))^3
f = (3 * k) + 3/2
g = math.pow(640320, f)
numerator = (a*b*c)
denominator = (d*e*f)
s += (numerator / denominator)
s *= 12
print(1 / s)
Here is my updated code:
import math
def fact(exi):
memory = exi
for i in range(1, exi):
memory *= i
return memory
k = 17
s = 0
for i in range(1, k):
a = (-1)**i
b = fact(6*i)
c = (545140134*i) + 13591409
d = fact(3*i)
e = (fact(i))**3
f = (3 * i) + 3/2
g = math.pow(640320, f)
num = (a*b*c)
den = (d*e*g)
s += (num / den)
s *= 12
print(1 / s)
I see two mistakes:
When comparing with the formula shown on Wikipedia, it looks like you should use the iteration variable i (named q in the formula) where you currently use k in the loop. In your code k is the upper bound for i.
The exponentiation operator in Python is **, not ^ (which is bitwise XOR).
Here is my code:
E = 2.7182818284590452353602875
n = int(input())
print(round(E,n))
For example, I need to round this to 24 decimal
But it`s gives just:
E = 2.71828182845
#No more
How to fix this?
Do not use Python float for this task because it will lose numbers due to precision. Use decimal module:
from decimal import Decimal
E = Decimal('2.7182818284590452353602875')
n = int(input())
print(E.quantize(Decimal('1.' + '0' * n)))
Output:
2.718281828459045235360288
As ingvar mentions the decimal module is necessary to get this level of precision. That said, you can also let it do the work of generating e in the first place via the exp recipe included in the docs, so you don't have to hardcode a specific value:
from decimal import localcontext, Decimal
def exp(x):
"""Return e raised to the power of x. Result type matches input type.
>>> print(exp(Decimal(1)))
2.718281828459045235360287471
>>> print(exp(Decimal(2)))
7.389056098930650227230427461
>>> print(exp(2.0))
7.38905609893
>>> print(exp(2+0j))
(7.38905609893+0j)
"""
with localcontext() as ctx:
ctx.prec += 2
i, lasts, s, fact, num = 0, 0, 1, 1, 1
while s != lasts:
lasts = s
i += 1
fact *= i
num *= x
s += num / fact
return +s
n = int(input())
with localcontext() as ctx:
ctx.prec = n + 1 # Use exactly the precision needed (one more than requested as 2 counts)
print(exp(Decimal(1)))
which, given an input of 24, outputs:
2.718281828459045235360287
Try it online!
I am trying to implement the Karatsuba Algorithm as mentioned in the course here in python 2.7. Here is the code that I have got currently:
# Karatsuba multiplication implementation in python
import numpy as np
import sys
# x = 10^(n/2)*a + b and y = 10^(n/2)*c + d
# x.y = 10^n*(ac) + 10^(n/2)*(ad + bc) + bd
# now recursively compute ac, ad, bc and bd
sys.setrecursionlimit(15000)
def algo_recurs(val1, val2):
# Assuming that the length of both the multiplier and multiplicand is
same
# Currently employing numbers which are of length 2^n
n = len(str(val1)) # n = 4
print(n)
divVal = 10**(n/2)
a = val1 / divVal # a = 12
b = val1 % divVal # b = 34
c = val2 / divVal # c = 43
d = val2 % divVal # d = 21
# let the example case be 1234 * 4321
if(len(str(val1)) == 2):
prob1 = a * c
prob2 = b * d
prob3 = (a+b)*(c+d) - prob1 - prob2
finalResult = prob1*(divVal*divVal)+prob3*divVal+prob2
return(finalResult)
else:
prob1 = algo_recurs(a,c)
prob2 = algo_recurs(b,d)
prob3 = algo_recurs((a+b),(c+d)) - prob1 -prob2
finalResult = prob1*(divVal*divVal)+prob3*divVal+prob2
#print(finalResult)
return(finalResult)
#Enter the inputs
multiplicand = input("Enter the multiplicand:")
multiplier = input("Enter the multiplier:")
output = algo_recurs(multiplicand, multiplier)
print(output)
The above code works well with the numbers of length 4 or less. But the moment I go beyond that, it throws the following error:
File "Karatsuba.py", line 31, in algo_recurs
prob1 = algo_recurs(a,c)
File "Karatsuba.py", line 31, in algo_recurs
prob1 = algo_recurs(a,c)
File "Karatsuba.py", line 31, in algo_recurs
prob1 = algo_recurs(a,c)
File "Karatsuba.py", line 15, in algo_recurs
n = len(str(val1)) # n = 4
RuntimeError: maximum recursion depth exceeded while getting the str of an object
I increased the recursion limit too, thinking that it might have been the issue. But that didn't solve it either.
I would appreciate if you can point out what I might be doing wrong in the implementation.
Your algorithm will never terminate, no matter how high you set the recursion limit. This is because the parameters a and c will always stay the same once val1 gets to single digits, because then n is 1 and 10**(n/2) is also 1.
It's dangerous to change the recursion limit because typically when you have exceeded the recursion limit, it's because your program contains an error or a poor design decision. Recursion can always be replaced with iteration at equal or lower memory cost.
Unless your algorithm insists you to do so knowing that at some point you will receive a result, you can change the maximum recursion depth every time you call your function, but again I wouldn't recommend since your program exceeded 1500 recursive calls when you set it to that and that is quite excessive.
# Karatsuba multiplication implementation in python
import numpy as np
import sys
def algo_recurs(val1, val2):
sys.setrecursionlimit(sys.getrecursionlimit() + 1) # Changes the recursion limit every time
n = len(str(val1))
#print(n)
divVal = 10**(n/2)
a = val1 / divVal # a = 12
b = val1 % divVal # b = 34
c = val2 / divVal # c = 43
d = val2 % divVal # d = 21
if(len(str(val1)) == 2):
prob1 = a * c
prob2 = b * d
prob3 = (a+b)*(c+d) - prob1 - prob2
finalResult = prob1*(divVal*divVal)+prob3*divVal+prob2
return(finalResult)
else:
prob1 = algo_recurs(a,c)
prob2 = algo_recurs(b,d)
prob3 = algo_recurs((a+b),(c+d)) - prob1 -prob2
finalResult = prob1*(divVal*divVal)+prob3*divVal+prob2
return(finalResult)
multiplicand = int(input("Enter the multiplicand:"))
multiplier = int(input("Enter the multiplier:"))
output = algo_recurs(multiplicand, multiplier)
print(output)
i need to write a script that get input from client of an number and i need to print back the PI number until client number
for example: client number is 52 --> 3.14159265358979323846264338327950288419716939937510
so far i write this:
sum = 0
for i in range(1, 1001):
sum += ((-1)**(i+1))*4 / ((i + i)*(i + i + 1)*(i + i + 2))
print(sum)
the issue is that python showing to me only the 17 decimals digits, and i expect to see the 1000 decimal digits.
there is a way to showing all the decimal digits based on the inputed range?
it's for school task, so i need to write is as simple as it can be.
I do not think it is possible to get a a float value with a 1000point precision.
Check https://stackoverflow.com/a/54967370/11152011 to calculate pi up to n-precision
You can then use the "decimal" library to use the string as a number.
The calculation of pi was taken from the above link.
import decimal
DIGITS = 1000
def pi_digits(x):
k,a,b,a1,b1 = 2,4,1,12,4
while x > 0:
p,q,k = k * k, 2 * k + 1, k + 1
a,b,a1,b1 = a1, b1, p*a + q*a1, p*b + q*b1
d,d1 = a/b, a1/b1
while d == d1 and x > 0:
yield int(d)
x -= 1
a,a1 = 10*(a % b), 10*(a1 % b1)
d,d1 = a/b, a1/b1
digits = [str(n) for n in list(pi_digits(DIGITS))]
str_pi='{}.{}'.format(digits.pop(0), "".join(digits)
context = decimal.Context(prec=100)
decimal.setcontext(context)
pi = decimal.Decimal(str_pi)
print(pi+5)
print(pi*20)
I don't know how accurate is this but for a small class assignment i guess do the following:
num=52 #input
pi=22/7;
print('{:.{}f}'.format(pi, num))
I was trying to compute e (2.718283) in python and I realized you couldn't simply divide so I defined a function to divide and round to five digits and I also defined a function to find factorials , here it is -
.
def div(x,y):
t = x + 0.00
p = y + 0.00
a = t / p
round(a,5)
print a
def fact(n):
c = 1
d = 1
while c < n:
p = c * d
d = c*d
c = c + 1
if c >= n:
break
p = p*n
print p
m = 0
while m < 20:
e = div(1,fact(m)) + q
q = div(1,fact(m + 1)) + q
if m >= 20:
break
print e `
I execute it and I get this UnboundLocalError: local variable 'p' referenced before assignment . But fact(3) seems to be working perfectly ..
What is going on ?
PS : i'm not yet used to formatting here but I have indented properly in the actual code
EDIT : as requested
line 20, in <module>
e = div(1,fact(m)) + q
File "/home/anirudh/Desktop/TEST PY/Hark-1.py", line 16, in fact
p = p*n
UnboundLocalError: local variable 'p' referenced before assignment
There are a couple of bugs:
q isn't defined anywhere before it's used in e = div(1,fact(m)) + q
You don't assign the result of round(a,5) to anything.
If the while c < n: loop isn't entered, p won't be defined when p = p*n is executed.
Both the fact and the div functions don't return anything. (They implicitly return None.)
There's no need to check if m >= 20:.
See, first of all there are already some cleaner and descent inbuilt methods in Python for calculating the factorial.
import math
print math.factorial(3) #6
print math.factorial(4) #24
And if you want to get the float value after dividing two integers then, you can simply typecast any one of them to the float, it is not necessary to convert both of them.
float_ans = p/float(q)
#or
float_ans = float(p)/q
Using this information, you can calculate the value of e, by simply:
#Knowing the fact that e = 1 + 1/1! + 1/2! + 1/3! + 1/4! + 1/5! ....
import math
e = 0
"""
As factorial of 20 is a very large value and you won't require that much of
precision, I have cut down the no of iterations from 20 to 7 only, it also gives
you a fair amount of precision, you can always change the range to increase and
decrease the precision accordingly.
"""
for num in range(0,7):
e+=(float(1)/math.factorial(num))
print e
2.71805555556