I have made a Python 3 program to calculate pi for a school project, but it always stops at 16 decimal places. Is there a limit to the length of numbers in python? If so is there a language that I could use that will let me continue?
accuracy = int(input("accuracy: "))
current = 2
opperation = "+"
number = 3
count = 1
for i in range (accuracy):
if opperation == "-":
number = number - (4/(current*(current+1)*(current+2)))
opperation = "+"
elif opperation == "+":
number = number + (4/(current*(current+1)*(current+2)))
opperation = "-"
current += 2
print(str(count).zfill(8)) + ": " + str(number)
count += 1
There is no restriction if you are working with integers and Python 3.x. The precision you get using floating point numbers is however limited. A Python float (like 3.14) is really a C double, which have about 16 decimals of precision, as you say.
You can use the decimal module to create and work with other floating point numbers with arbitrary precision. Example code:
# Normal Python floats
a = 0.000000000000000000001
b = 1 + 2*a
print(b) # Prints 1.0
# Using Decimal
import decimal
decimal.getcontext().prec = 100 # Set the precision
a = decimal.Decimal('0.000000000000000000001')
b = 1 + 2*a
print(b) # Prints 1.000000000000000000002
See the docs for more information on decimal.
Related
Is there any way I can make the limitation to the whole number you can convert to binary endless without having to write endless repetitive code for each stage of the whole number to binary conversion.
#this is my first attempt at creating a integer to binary converter
#currently only works with 5 digit binary output
integer = int(input('Please input a whole number you would like converted in to binary '))
remainder_1 = (integer) % 2
division_1 = (integer) // 2
#print(remainder_1)
#print(f"d1 {division_1}")
remainder_2 = (division_1 % 2)
division_2 = (division_1 // 2)
if division_2 == 0 and remainder_2 == 0:
remainder_2 = ('')
#print(remainder_2)
#print(f"d2 {division_2}")
remainder_3 = (division_2 % 2)
division_3 = (division_2 // 2)
if division_3 == 0 and remainder_3 ==0:
remainder_3 = ('')
#print(remainder_3)
#print(f"d3 {division_3}")
remainder_4 = (division_3 % 2)
division_4 = (division_3 // 2)
if division_4 == 0 and remainder_4 ==0:
remainder_4 = ('')
#print(remainder_4)
#print(f"d4 {division_4}")
remainder_5 = (division_4 % 2)
division_5 = (division_4 // 2)
if division_5 == 0 and remainder_5 ==0:
remainder_5 = ('')
#print(remainder_5)
#print(f"d5 {division_5}")
remainder_6 = (division_5 % 2)
division_6 = (division_5 // 2)
if division_6 == 0 and remainder_6 ==0:
remainder_6 = ('')
#print(remainder_6)
#print(f"d6 {division_6}")
Binary = (f'{remainder_6}{remainder_5}{remainder_4}{remainder_3}{remainder_2}{remainder_1}')
print (Binary)
also when printing the binary result is there a way to repeat printing of remainders in order of most significant number to least significant number without having to write it all out as I did above up until remainder 6, Of course depending on how large the whole number input is initially.
integer = int(input('Please input a whole number you would like converted in to binary '))
binary = ""
# while integer is greater than zero.
while integer > 0:
# get the remainder of integer divided by 2.
remainder = str(integer % 2)
# concat the remainder as prefix to the binary string
binary = remainder + binary
# integer division by 2 on the integer
integer = integer // 2
print(binary)
Output
Please input a whole number you would like converted in to binary 100
1100100
I encountered an issue with my Python script that converts binary to decimals. The caveat with this script is that I can only use basic computational functions (+, -, *, /, **, %, //), if/else, and for/while loops.
Shown below is my script:
x = int(input("Enter your binary input: "))
z=0
while x != 0:
for y in range (0,20):
if (x % 2 == 0):
z += 0*2**y
x = int(x/10)
elif (x % 2 != 0):
z += 1*2**y
x = int(x/10)
print(z)
While my script works for binaries with short length (e.g., 1101 = 13), it does not work for long binaries (especially those that have a length of 20). For example, inputting a binary of 11111010010011000111, my script returns an output of 1025217 instead of 1025223.
Can anyone point me to my mistake?
Thank you in advance!
Floating arithmetic isn't perfect and has a precision limit.
11111010010011000111 / 10 gives 1.1111010010011e+18, which when converted to an integer will give you a wrong result and it snowballs from there.
>>> int(11111010010011000111 / 10)
1111101001001100032
The more binary digits you have, the more "off" your calcuations will be.
In order to avoid the problem you encountered, use floor division, ie, x // 10.
Or you can skip turning x into a number and do the necessary power calculations based off each binary digit and its position.
x = input("Enter your binary input: ")[::-1]
n = 0
# this would be more elegant with `enumerate()`, but I assume you can't use it
# same for `sum()` and a comprehension list
for i in range(len(x)):
n += int(x[i])*2**i
print(n)
You can use the following method
to multiple each of the binary digits with its corresponding value of 2 raised to the power to its index (position from right – 1) and sum them up.
binary = input('Binary number: ')
decimal = 0
binary_len = len(binary)
for x in binary:
binary_len = binary_len - 1
decimal += pow(2,binary_len) * int(x)
print(decimal)
input : 11111010010011000111
output : 1025223
More examples
You should not use int to convert any number if you have to write a number converter.
Just use string operations:
digits = input("Enter your binary input: ")
number = 0
for digit in digits:
number = number * 2 + (digit == "1")
print(number)
output
Enter your binary input: 11111010010011000111
1025223
I am trying to define a function to convert a binary number to a decimal number and check if it is an absolute square or not. I am passing a list of binary numbers as the argument and the function is supposed to print "True" or "False" as the output in the same order as that of the list elements; depicting whether or not they are absolute squares.
While trying so I am getting a syntax error in the ninth line where I am trying to calculate the decimal equivalent of the binary digits by adding the individual values arising out of each binary digit owing to it's position.
Logic of Execution: 1001 in Binary means [pow(2,3)*1 + pow(2,2)*0 + pow(2,1)*0 + pow(2,0)*1] in Decimal. It's equal to 9 which is an absolute square of 3. So the output should be "True"
import math
n = int(input("Enter the total no of elements to check: "))
num_list = []
for k in range (n):
print("Enter the number at position "+str(k)+" : ")
num = int(input())
num_list.append(num)
#print(num_list) for debugging purpose
def Binary_SquareRoot_Checker(input_list):
for i in input_list:
q = str(i)
no_of_digit = len(q)
#For each element of the list, we need to count the no of digits present
addition_num = 0
for p in range (no_of_digit):
r = q[p]
value = (2**(no_of_digit - (p+1)) * int(r)
addition_num = addition_num + value
#print(addition_num) just to see the decimal number
root = math.sqrt(sum_num)
if int(root + 0.5) ** 2 == sum_num:
#Checking for absolute square property
print("True")
else:
print("False")
Binary_SquareRoot_Checker(num_list)
I am getting Syntax Error at addition_num = addition_num + value
Please tell me why this error is being reported?
In the 20th line, change:
value = (2**(no_of_digit - (p+1)) * int(r)
To:
value = (2**(no_of_digit - (p+1)) * int(r) )
So I am meant to write a program that will convert a decimal to a binary and then another that will do the opposite. I know there are python functions to do this, but I think we are meant to do it the longer way. The pseudocode goes like this:
Decimal to Binary:
number = Prompt user for input, convert to int
Set quotient equal to number, remainder equal to zero
while(number!=0)
(quotient,remainder)=divmod(quotient,2)
print(remainder)
Binary to Decimal
number=Prompt user for input
Get string length of number = n
for x in range(n)
sum+=(2^n) times x
print sum
Any help?
Codes for manually converting. Am using loops here. It can be done using recursion too.
#Binary to Decimal
def btod(binary):
decimal = 0
for digit in binary:
decimal = decimal*2 + int(digit)
return decimal
#Decimal to Binary
def dtob(decimal):
if decimal == 0:
return 0
binary=''
decimal = int(decimal) #incase arg is int
while (decimal > 0):
binary+= str(decimal%2)
decimal = int(decimal/2)
return binary[::-1] #reverse the string
print(btod('101'))
#5
print(dtob('5'))
#101
The translation dictionary for your pseudo-code:
"Prompt user for input, convert to int":
int(input("Enter a decimal number: "))
"Set quotient equal to number, remainder equal to zero":
quotient = number
remainder = 0
"divmod(quotient,2)":
quotient // 2, quotient % 2
"Prompt user for input":
input("Enter a binary number: ")
"Get string length of number = n":
n = len(number)
"(2^n) times x":
2**n * x
"print sum":
print(sum)
Use this dictionary for replacing the corresponding parts in your pseudo-code. All other parts keep in their place, including indentations.
Note:
By your pseudo-code your program "Decimal to Binary" will print the converted decimal number in the column - read the result from bottom to top.
I have written an transfomator for decimal numbers in an other number system. The number left to the comma i right but the decimal place after the comma is false. I'll poste my code but the variables are in german, so i hope you can read them
here ist the code left to the comma (no mistake)
print "decimal numbers to another number system between [2-9]\n"
decimal = float(raw_input("put in a float: "))
base = int(raw_input("base: "))
#declaration for first part
decimalnew = decimal # we need this var for the second part
result = 0
number = int(decimal) / 1
factor = 1
# first part for integers decimal is always an integer (this part is ok)
while (decimal):
leftover = int(decimal) % base
decimal = int(decimal) / base
factor *= 10
result = result + leftover * factor
#declaration for second part
decimalnew = decimalnew - number
result2 = 0
factor2 = 1
# second part for floats always < 1 (f.e. 0.2)
# i think in this part is the mistake
while (decimalnew > 0):
leftover2 = decimalnew * base
decimalnew = decimalnew * base
if (decimalnew > 0):
decimalnew = decimalnew - leftover2
factor2 = factor2 * 10
result2 = result2 + leftover2 / factor2
# results from the first part and the second part
finalresult = result + result2
print "eingegebene Zahl", number, "- neue Zahl mit der Basis %d =" % (base) , finalresult/10
First, as you use only 0-9 numbers, you cannot process basis greater than 10.
But you have some problems with the decimal part. First is that even if it worked your algorythme has high chance to break because it can lead to inifinite values.
As a simple example : 0.1 in basis 4 gives the infinite value : 0.0121212..
So you must, first add another question for the maximum precision to stop an eventual infinite loop, an next the algorithme for the decimal part must be rewritten.
The following should work :
print "reeller Dezimal-Konvertierer\n"
dezimal = float(raw_input("Bruchzahl eingeben: "))
basis = int(raw_input("Basis eingeben: "))
dezpos = int(raw_input("Maximal precision: ")) # don't know how to spell it in german
dezimalneu = dezimal
ergebnis = 0
zahl = int(dezimal) / 1
faktor = 1
while (dezimal):
rest = int(dezimal) % basis
dezimal = int(dezimal) / basis
faktor *= 10
ergebnis = ergebnis + rest * faktor
dezimalneu = dezimalneu - zahl
ergebnis2 = 0
faktor2 = 1
while (dezimalneu > 0) and dezpos > 0:
print dezimalneu
dezimalneu *= basis
faktor2 *= 10
i = int(dezimalneu)
ergebnis2 = ergebnis2 *10 + i
dezimalneu -= i
dezpos -= 1
ergebnis2 = 1.0 * ergebnis2 / faktor2
ergebnisfinal = ergebnis + ergebnis2
print "eingegebene Zahl", zahl, "- neue Zahl mit der Basis %d =" % (basis) , ergebnisfinal/10
(I kept the german variable names, because I have begun to write it before it was translated)
The subtraction is wrong. dezimalnew == rest2, if you look closely at the assignment, so it will give 0.
What I'd say is that you may need to review in general how to convert from a decimal floating number to any base. The general idea, is once you have the 0.1 for example (the floating part), you want to keep multiplying by the base and adding the INTEGER part of the new result to the converted number, then keeping only the new decimal part.
For example, 0.1 to 3 gives 0.002200... because:
0.1 * 3 = (0).3 * 3 = (0).9 * 3 = (2).7, 0.7 * 3 = (2).1, 0.1 * 3 = 0.3...