I'm trying this example:
p = 10000
n = 12
r = 8
t = int(input("Enter the number of months the money will be compounded "))
a = p (1 + (r/n)) ** n,t
print (a)
.. but the error is:
TypeError: 'int' object is not callable
Is Python seeing p as a function? If so, is there no way I could do it without importing modules?
Thanks!
Change the line to
a = p * (1 + (r/n)) ** (n * t)
Python doesn't interpret variables that are next to each other as being multiplied (nor would it interpret n, t as that.
Assuming you are using python 3..
p = 10000
n = 12
r = 8
t = int(input("Enter the number of months the money will be compounded: "))
a = p * (1 + (r / n)) ** (n * t)
print(a)
Also double check the units for t, is it in months or years? The formula seems to suggest years (if n = 12 is months per year) but you are prompting for months.
If in python 2.x you would need to import division from __future__, or convert r to float first. And you would use raw_input for the prompt.
You are trying to multiply by p, so you should be explicit and use a *:
a = p * ((1 + (float(r)/n)) ** n,t)
Cast to float (thanks David R) to prevent int rounding problems in division.
you need the "*" operator to multiply numbers
dividing int by int does not give a float so cast one to a float multiply of divide by a float (you will see "*1." in some code to do this"
your input line does not match the variables above (i.e. t should be years not months and n is number of times compounded per year ... 12 for monthly and 4 for quarterly etc)
also need to change your 8 to .08 as a percentage
Try:
p * (1 + (r/100.0/n)) ** (n * t)
Related
This question already has answers here:
What does the ** maths operator do in Python?
(5 answers)
Closed 1 year ago.
I want to find the 5th power of a number given by the user. Can i do this without typing:
ans = n * n * n * n * n
and can it be used for higher powers?
Use the ** operator for exponents:
print(5**12)
>>> 224832
We can use this more generally using variables.
exponent = 5
n = 12
ans = n ** exponent
print(ans)
>>> 248832
Other Methods
Since the ** operator caps at an exponent of 256, we can use the built-in pow() function for larger exponents. However, these numbers can be very large.
power = pow(base, exponent)
The math and numpy libraries also can do this using the math.pow() and numpy.power() functions.
An alternative to the ** operator is to use the math library functions.
import math
math.pow(x, y)
Note that this returns a floating point value, while the ** operator will return an int or float based on the type of x.
I want to write a function that calculate (1 / n!) * (1! + 2! + 3! + ... + n!) with n as the parameter of the function, also the result is truncated to 6 decimals (not rounded).
Below is my code:
def going(n):
n1 = n
n2 = n
factorial = 1
back = 1
for i in range(2, n1+1):
factorial *= i
while n2>1:
this = 1
for i in range(2, n2+1):
this*=i
back+=this
n2 = n2-1
this = 1
result = int((1/factorial)*back*1000000)/1000000
return result
When I passed the argument 171 into the function, I got the following traceback:
Traceback (most recent call last):
File "/Users/Desktop/going.py", line 18, in <module>
print(going(171))
File "/Users/Desktop/going.py", line 15, in going
result = int((1/factorial)*back*1000000)/1000000
OverflowError: int too large to convert to float
How can I fix this problem? Thanks a lot for help!
--update--
Sorry that I didn't clarify: I'm doing this problem in Codewars and I don't think I can import any libraries to use. So, I need a solution that can avoid using any libraries.
Original problem from Codewars:
Consider the following numbers (where n! is factorial(n)):
u1 = (1 / 1!) * (1!)
u2 = (1 / 2!) * (1! + 2!)
u3 = (1 / 3!) * (1! + 2! + 3!)
un = (1 / n!) * (1! + 2! + 3! + ... + n!)
Which will win: 1 / n! or (1! + 2! + 3! + ... + n!)?
Are these numbers going to 0 because of 1/n! or to infinity due to the sum of factorials?
Task
Calculate (1 / n!) * (1! + 2! + 3! + ... + n!) for a given n, where n is an integer greater or equal to 1.
To avoid discussions about rounding, return the result truncated to 6 decimal places, for example:
1.0000989217538616 will be truncated to 1.000098
1.2125000000000001 will be truncated to 1.2125
Remark
Keep in mind that factorials grow rather rapidly, and you need to handle large inputs.
And going(170) works as intended, right?
What you are seeing is a fundamental limitation of how your computer represents floating point numbers, and not a problem with Python per se. In general, most modern computers use IEEE 754 to represent and perform math with non-integer numbers. Specifically, numbers using IEEE 754's "binary64" (double-precision) floating point representation has a maximum value of 2^1023 × (1 + (1 − 2^−52)), or approximately 1.7976931348623157 × 10^308. It turns out that 170! ≈ 7.2 × 10^306, which is just under the maximum value. However, 171! ≈ 1.2 × 10^309, so you are out of luck.
The best chance you have of actually performing calculations with numbers that large without running into these overflow errors or losing precision is to use a large number library like gmpy2 (see this previous answer). A possible solution would be:
from gmpy2 import mpz, add, div, fac
def going(n):
factorial = fac(n)
back = mpz(1)
for i in range(2, n+1):
back = add(back, fac(i))
result = div(back, factorial)
return result
#PaSTE's suggestion to use gmpy2 is great, and should work fine.
The library mpmath is built on top of gmpy2 and provides the function ff (falling factorial) that makes the implementation a little more concise:
import mpmath
def going_mp(n):
return sum([1/mpmath.ff(n, k) for k in range(n)])
For example,
In [54]: import mpmath
In [55]: mpmath.mp.dps = 30
In [56]: going_mp(170)
Out[56]: mpf('1.00591736819491744725806951204519')
In [57]: going_mp(171)
Out[57]: mpf('1.00588255770874220729390683925161')
(I left out the truncating of the digits. That's something that you can add as you see fit.)
Another standard technique for handling very large numbers is to work with the logarithms of the numbers instead of the numbers themselves. In this case, you can use math.lgamma to compute k!/n! as exp(lgamma(k+1) - lgamma(n+1)). This will allow you to compute the value using just the standard math library.
import math
def going_l(n):
lognfac = math.lgamma(n + 1)
return sum([math.exp(math.lgamma(k+1) - lognfac) for k in range(1, n+1)])
For example,
In [69]: going_l(170)
Out[69]: 1.0059173681949172
In [70]: going_l(171)
Out[70]: 1.0058825577087422
Finally, if you don't want to use even the standard library, you could avoid the large numbers another way. Rewrite the expression as
1 1 1 1
1 + - + ------- + ------------- + ... + ---
n n*(n-1) n*(n-1)*(n-2) n!
That leads to this implementation:
def going_nolibs(n):
total = 0.0
term = 1.0
for k in range(n, 0, -1):
total += term
term /= k
return total
For example,
In [112]: going_nolibs(170)
Out[112]: 1.0059173681949174
In [113]: going_nolibs(171)
Out[113]: 1.0058825577087422
This question already has answers here:
How do I use a decimal step value for range()?
(34 answers)
Closed 4 years ago.
I'm relatively new to Python, so my code is very simple.
I have a project to write code which approximates integrals using the rectangle rule, followed by the trapezium rule:
a = float(input('Lower limit ---> '))
while True:
b = float(input('Upper limit ---> '))
if b > a:
break
elif a == b:
print('Integral = 0.')
else:
print('Invalid input.')
N = float(input('Number of integral divisions ---> '))
h = float((b - a) / N)
print('For the integral in the range {} to {} with {} divisions, the step size is {}.'.format(a,b,N,h))
def f(x):
return(np.exp(-x) * sin(x))
summation = (f(a) + f(b))
for points in range(a, N - 1):
summation = summation + f(a + (points * h))
I = h * summation
print(I)
Near the end, I try to use a for loop from the initial limit to minus 1 the number of step sizes.
I've defined this as a float but it I keep getting the error
TypeError: 'float' object cannot be interpreted as an integer.
Any ideas how to fix this?
when you collect your a and N variables, you convert them in float:
a = float(input('Lower limit ---> '))
N = float(input('Number of integral divisions ---> '))
Then you try to iterate from a to N, but let's assume a=0.42 and n=3.14.
How do you expect python to behave?
print([x for x in range(0.42,3.14)]) # Raise TypeError: 'float' object cannot be interpreted as a
so you have to convert your float into integers (a = int(a), N = int(N)):
print([x for x in range(0,3)]) # prints [0, 1, 2]
or you can use numpy, and define 2 float values and the step between them:
import numpy as np
np.arange(0.0, 1.0, 0.1)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
a, b and N are floats. range does not allow its arguments to be floats so you will need to convert them to int:
for points in range(int(a), int(N - 1)):
The error message clearly states that you are using floats where an integer is wanted.
Read the documentation of range() - what lead you to believe is is capable of doing anything with floats?
There are unlimited floats between 1 and 2 - and still very many if you take the resolution of float into consideration - how should python be able to give you all of them as range?
def f(n):
Total_Triangles = 0
for i in range(1,n+1):
term = 3**(i-1)
Total_Triangles+=term
return Total_Triangles
Q = int(input())
for i in range(Q):
n = int(input())
Ans = f(n)*4 +1
print(Ans%1000000007)
How to tackle with Time limit error in this code?
Karan has a good answer. It will speed up your original approach, but you still end up calculating huge numbers. Fortunately, Python's Long type can do that, but I expect that it isn't as efficient as the native 32-bit or 64-bit integer types.
You are told to give the answer modulo a huge number M, 1,000,000,007. You can improve the algorithm by using modular arithmetic throughout, so that your numbers never get very big. In modular arithmetic, this is true:
(a + b) % M == (a % M + b % M) % M
(a * b) % M == (a % M * b % M) % M
One approach could be to calculate all possible Q values up front using modular arithmetic:
M = 1000000007
def makef(m):
"""Generator to create all sum(3**i) mod M"""
n = 1
s = 0
for i in range(m):
yield s
s = (s + n) % M
n = ((n + n) % M + n) % M
f = list(makef(100000))
Q = int(input())
for i in range(Q):
n = int(input())
print (f[n] * 4 + 1) % M
This will do the calculations in a big loop, but only once and should be fast enough for your requirements.
Python offers you a second way: The expression a ** b is mapped to the in-built function pow(a, b). This function can take a third parameter: a base for modular arithmetic, so that pow(a, b, M) will calculate (a ** b) % M without generating huge intermediate results.
Now you can use Karan's neat formula. But wait, there's a pitfall: You have to divide the result of the power by two. The modular relationships above are not true of division. For example, (12 // 2) % M is 6, but if you applied the modulo operator first, as the pow function does, you'd get ((12 % 2) // 2) % M, which is 1 and not what you want. A solution is to calculate the power modulo 2 * M and then divide by 2:
def f(n):
return pow(3, n, 2 * 1000000007) // 2
Q = int(input())
for i in range(Q):
n = int(input())
print (f(n) * 4 + 1) % M
(Note that all powers of 3 are odd, so I have removed the - 1 and let the integer division do the work.)
Side note: The value of M is chosen so that the addition of two numbers that are smaller than M fits in a signed 32-bit integer. That means that users of C, C++ or Java don't have to use bignum libraries. But note that 3 * n can still overflow a signed int, so that you have to take care when multiplying by three: Use ((n + n) % M + n) % M instead.
You want to find 3 ** 0 + 3 ** 1 ... + 3 ** (n - 1), this is just a geometric series with first term a = 1, common ratio r = 3 and number of terms n = n, and using the summation of a geometric series formula, we can find f(n) much faster when defined as so:
def f(n):
return (3 ** n - 1) // 2
I am writing a program that handles numbers as large as 10 ** 100, everything looks good when dealing with smaller numbers but when values get big I get these kind of problems:
>>> N = 615839386751705599129552248800733595745824820450766179696019084949158872160074326065170966642688
>>> ((N + 63453534345) / sqrt(2)) == (N / sqrt(2))
>>> True
Clearly the above comparision is false, why is this happening?
Program code:
from math import *
def rec (n):
r = sqrt (2)
s = r + 2
m = int (floor (n * r))
j = int (floor (m / s))
if j <= 1:
return sum ([floor (r * i) for i in range (1, n + 1)])
assert m >= s * j and j > 1, "Error: something went wrong"
return m * (m + 1) / 2 - j * (j + 1) - rec (j)
print rec (1e100)
Edit:
I don't think my question is a duplicate of the linked question above because the decimal points in n, m and j are not important to me and I am looking for a solution to avoid this precision issue.
You can’t retain the precision you want while dividing by standard floating point numbers, so you should instead divide by a Fraction. The Fraction class in the fractions module lets you do exact rational arithmetic.
Of course, the square root of 2 is not rational. But if the error is less than one part in 10**100, you’ll get the right result.
So, how to compute an approximation to sqrt(2) as a Fraction? There are several ways to do it, but one simple way is to compute the integer square root of 2 * 10**200, which will be close to sqrt(2) * 10**100, then just make that the numerator and make 10**100 the denominator.
Here’s a little routine in Python 3 for integer square root.
def isqrt(n):
lg = -1
g = (1 >> n.bit_length() // 2) + 1
while abs(lg - g) > 1:
lg = g
g = (g + n//g) // 2
while g * g > n:
g -= 1
return g
You should be able to take it from there.