python problems with decimal place - python

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...

Related

calculator that prints step by step solution in python

my son is trying to make a calculator to help him with the many pages of homework that he gets. I know the simple solution would be to tell him about wolfram alpha, but I thought this could be a fun project. I need some help with how to iterate over the rest of the digits and print the solution in a step-by-step format. This is what he has so far:
# Variables
X = input("input the first number with space between digits: ")
Y = int(input("input the second number: "))
Xn = X.split(" ")
if int(Xn[0]) >= Y: # if Y fits in X the do a simple division and return the remainder
Xy1 = int(Xn[0])
fit0 = int(Xy1 / Y)
rem0 = Xy1 - fit0 * Y
print(" It fits " + str(fit0), "times ", " the remainder is: " + str(rem0))
else: # if Y does not fit in X the add the first two strings of X and convert them to integers then do a simple
# division and return the remainder
Xy0 = (int(Xn[0] + Xn[1]))
fit = int(Xy0 / Y)
rem = Xy0 - fit * Y
print(" It fits " + str(fit), "times ", " the remainder is: " + str(rem))
Here, I made an example that prints step by step the division.
I hardcoded the x (dividend with digits separated by spaces) and the divisor.
You can just change it to incorporate the inputs from the user
x = "1 4 8 7"
divisor = 5
# convert x to a list of integers
x = [int(i) for i in x.split(" ")]
dividend = x[0]
i = 0 # index of the current dividend digit
quotient = ""
while i < len(x)-1:
i += 1
quotient += str(dividend // divisor)
remainder = dividend % divisor
print(f"{dividend} / {divisor} -> {dividend // divisor} (remainder {remainder})")
dividend = remainder * 10 + x[i]
quotient += str(dividend // divisor)
remainder = dividend % divisor
print(f"{dividend} / {divisor} -> {dividend // divisor} (remainder {remainder})")
print(f"Result: {quotient} (remainder {remainder})")
This gives as result:
1 / 5 -> 0 (remainder 1)
14 / 5 -> 2 (remainder 4)
48 / 5 -> 9 (remainder 3)
37 / 5 -> 7 (remainder 2)
Result: 297 (remainder 2)
I think I misunderstood the question... why not use float?
x = float(input("input the first number: "))
y = float(input("input the second number: "))
print(f" It fits {x//y} times , the remainder is: {x/y-x//y}")

Division by zero using // operator in python

Running the following code:
p = int(input("principal: "))
interest = int(input("annual interest rate: "))
years = int(input("# of years: "))
r = interest // 100
n = years * 12
top = r * (1 + r) ** n
bottom = (1+r) ** n - 1
fraction = top // bottom
A = fraction * p
print(A)
I get:
line 17, in <module>
fraction = top // bottom
ZeroDivisionError: integer division or modulo by zero
I am a beginner, please be kind!
The floor division // rounds the result down to the nearest whole number (data type = integer) and r as an integer will be 0 when interest is <100.
You can see what happens with top if r equals 0.
Same thing with fraction and the // operator. Use round to round the numbers.
p = int(input("principal: "))
interest = int(input("annual interest rate: "))
years = int(input("# of years: "))
r = interest / 100
n = years * 12
top = r * (1 + r) ** n
bottom = (1+r) ** n - 1
fraction = top / bottom
A = round(fraction * p, 2)
print(A)

Syntax Error while Summation Operation in for loop of Python

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) )

Are there number limitations in python?

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.

Why is my decimal to binary program returning the value backwards and in a table format?

I'm using python 3.5.2 to make this program. It'supposed to take any decimal number and convert it to binary.
number = int(input('Enter a number in base 10: '))
base2 = ''
while(number > 0):
rem = number % 2
number = number // 2
base2 = srt(number) + str(rem)
print(rem)
#This was to prevent the end text from sticking to the print
input('\nEnter to end')
It returns the correct values, but backwards and in a column and I don't know why.
Some modifications to your code:
number = int(input('Enter a number in base 10: '))
base2 = ''
while(number > 0):
rem = number % 2
number = number // 2 # can be number //= 2, or number >>= 1
base2 += str(rem)
#print(rem) # no need to print
print(base2[::-1])
Or more simple:
base2 = bin(number)[2:]
Your code prints the lowest bit of remaining number on separate lines so that's why you see them in reverse order. You could change your code to store bits to an array and then after the loop print them in reverse order:
number = int(input('Enter a number in base 10: '))
base2 = []
while(number > 0):
base2.append(str(number % 2))
number = number // 2
print(''.join(reversed(base2)))
Python also has built-in method bin than can do the conversion for you:
>>> bin(10)
'0b1010'

Categories