Division by zero using // operator in python - 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)

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

Python Converting picoseconds and femtoseconds not giving the right time in seconds

I'm converting from all units of time to seconds and for some reason with the smaller units of time (picoseconds and femtoseconds), i'm getting (femtoseconds): 0.00000000000000100000000000000007770539987666107923830718560119501514549256171449087560176849365234375 instead of 0.000000000000001. Does anyone know why?
days = int(input("Enter the amount of days: ")) * 24 * 60 * 60
hours = int(input("Enter the amount of hours: ")) * 60 * 60
minutes = int(input("Enter the amount of minutes: ")) * 60
ms = int(input("Enter the amount of milliseconds: ")) * (10 ** -3)
mcs = int(input("Enter the amount of microseconds: ")) * (10 ** -6)
ns = int(input("Enter the amount of nanoseconds: ")) * (10 ** -9)
ps = int(input("Enter the amount of picoseconds: ")) * (10 ** -12)
fs = int(input("Enter the amount of femtoseconds: ")) * (10 ** -15)
s = days + hours + minutes + ms + mcs + ns + ps + fs
print("The amount of seconds is:", "{0:.50}".format(s))
Floating point numbers cannot be accurately represented in any programming language, simply because there is an infinite number of them. However, what might help you is Decimal: Clarification on the Decimal type in Python
Documentation: https://docs.python.org/3.8/library/decimal.html

Get the last n digits of a long

My program asks user to enter a power and how many digits they want. And finds the last that many digits of 2 raised to the power the user entered.
My code looks like this. I am just a beginner in python. I am not getting the output desired.
temp = int(input('Enter the power of the number: '))
temp2 = int(input('Enter the no.of digits you want: '))
temp3 = (2 ** temp) // temp2
temp4 = (temp3 % 100)
print('The last that many digits of the number raised to the power is is:',temp4)
I am assuming you are looking for something like this:
power: 8
digits: 2
2 ^ 8 = 256
last two digits = 56
To do this your code would look like this:
power = int(input('two to the power of '))
digits = int(input('last how many digits? '))
num = 2 ** power # calculate power
num = num % (10 ** digits) # get remainder of division by power of 10
print(num)
Here's another approach:
power = int(input('two to the power of '))
digits = int(input('last how many digits? '))
num = 2 ** power # calculate power
num = str(num) # convert with string to work with
num = num[-digits:] # get last n digits
num = int(num)
print(num)

Loan payment calculation

I am learning Python and am stuck. I am trying to find the loan payment amount. I currently have:
def myMonthlyPayment(Principal, annual_r, n):
years = n
r = ( annual_r / 100 ) / 12
MonthlyPayment = (Principal * (r * ( 1 + r ) ** years / (( 1 + r ) ** (years - 1))))
return MonthlyPayment
n=(input('Please enter number of years of loan'))
annual_r=(input('Please enter the interest rate'))
Principal=(input('Please enter the amount of loan'))
However, when I run, I am off by small amount. If anyone can point to my error, it would be great. I am using Python 3.4.
Payment calculation-wise, you don't appear to have translated the formula correctly. Besides that, since the built-in input() function returns strings, you'll need to convert whatever it returns to the proper type before passing the values on to the function which expects them to numeric values.
def myMonthlyPayment(Principal, annual_r, years):
n = years * 12 # number of monthly payments
r = (annual_r / 100) / 12 # decimal monthly interest rate from APR
MonthlyPayment = (r * Principal * ((1+r) ** n)) / (((1+r) ** n) - 1)
return MonthlyPayment
years = int(input('Please enter number of years of loan: '))
annual_r = float(input('Please enter the annual interest rate: '))
Principal = int(input('Please enter the amount of loan: '))
print('Monthly payment: {}'.format(myMonthlyPayment(Principal, annual_r, years)))
I think in the last bit of your calculation,
/ (( 1 + r ) ** (years - 1))
you have your bracketing wrong; it should be
/ ((( 1 + r ) ** years) - 1)
I think the correct formula is this,
MonthlyPayment = (Principal * r) / (1 - (1 + r) ** (12 * years))
I cleaned up your variables some,
def get_monthly_payment(principal, annual_rate, years):
monthly_rate = annual_rate / 100 / 12
monthly_payment = principal * (monthly_rate + monthly_rate / ((1 + monthly_rate) ** (12 * years) - 1))
return monthly_payment
years = float((input('Please enter number of years of loan')))
annual_rate = float((input('Please enter the interest rate')))
principal = float((input('Please enter the amount of loan')))
print ("Monthly Payment: " + str(get_monthly_payment(principal, annual_rate, years)))
It would also be prudent to add a try-except block around the inputs.

python problems with decimal place

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

Categories