Python "int object is not callable" - python-3.x

TypeError: 'int' object is not callable
Anyone knows how can I fix this error? I know error is somewhere in the equation in the total. Thanks
decimal = 0
rate = 0
principal = 0
years = 0
def simple(p, r, n,):
decimal = r / 100
print("Principal: " + str(p))
print("Rate: " + str(decimal))
print("Number of Years: " + str(n))
total = p (1 + (decimal * n))
print("Total: " + str(total))
def main():
principal = int(input("Enter Principal: "))
rate = float(input("Enter Rate: "))
years = int(input("Enter Numbers of Years: "))
simple(principal, rate, years)
main()
print("End of Program")

Here p is an integer that you try to call :
total = p (1 + (decimal * n))
I think that you want :
total = p*(1 + (decimal * n))

On this line p is expected to be a function because it is immediately followed by a parenthesis:
total = p (1 + (decimal * n))
But p is passed as a parameter above, so I'm guessing you are passing an integer. If you mean to multiply:
total = p * (1 + (decimal * n))

You should define p first simple(int p,int r,int t) then total=p*(1+decim

Related

Simpson's rule 3/8 for n intervals in Python

im trying to write a program that gives the integral approximation of e(x^2) between 0 and 1 based on this integral formula:
Formula
i've done this code so far but it keeps giving the wrong answer (Other methods gives 1.46 as an answer, this one gives 1.006).
I think that maybe there is a problem with the two for cycles that does the Riemman sum, or that there is a problem in the way i've wrote the formula. I also tried to re-write the formula in other ways but i had no success
Any kind of help is appreciated.
import math
import numpy as np
def f(x):
y = np.exp(x**2)
return y
a = float(input("¿Cual es el limite inferior? \n"))
b = float(input("¿Cual es el limite superior? \n"))
n = int(input("¿Cual es el numero de intervalos? "))
x = np.zeros([n+1])
y = np.zeros([n])
z = np.zeros([n])
h = (b-a)/n
print (h)
x[0] = a
x[n] = b
suma1 = 0
suma2 = 0
for i in np.arange(1,n):
x[i] = x[i-1] + h
suma1 = suma1 + f(x[i])
alfa = (x[i]-x[i-1])/3
for i in np.arange(0,n):
y[i] = (x[i-1]+ alfa)
suma2 = suma2 + f(y[i])
z[i] = y[i] + alfa
int3 = ((b-a)/(8*n)) * (f(x[0])+f(x[n]) + (3*(suma2+f(z[i]))) + (2*(suma1)))
print (int3)
I'm not a math major but I remember helping a friend with this rule for something about waterplane area for ships.
Here's an implementation based on Wikipedia's description of the Simpson's 3/8 rule:
# The input parameters
a, b, n = 0, 1, 10
# Divide the interval into 3*n sub-intervals
# and hence 3*n+1 endpoints
x = np.linspace(a,b,3*n+1)
y = f(x)
# The weight for each points
w = [1,3,3,1]
result = 0
for i in range(0, 3*n, 3):
# Calculate the area, 4 points at a time
result += (x[i+3] - x[i]) / 8 * (y[i:i+4] * w).sum()
# result = 1.4626525814387632
You can do it using numpy.vectorize (Based on this wikipedia post):
a, b, n = 0, 1, 10**6
h = (b-a) / n
x = np.linspace(0,n,n+1)*h + a
fv = np.vectorize(f)
(
3*h/8 * (
f(x[0]) +
3 * fv(x[np.mod(np.arange(len(x)), 3) != 0]).sum() + #skip every 3rd index
2 * fv(x[::3]).sum() + #get every 3rd index
f(x[-1])
)
)
#Output: 1.462654874404461
If you use numpy's built-in functions (which I think is always possible), performance will improve considerably:
a, b, n = 0, 1, 10**6
x = np.exp(np.square(np.linspace(0,n,n+1)*h + a))
(
3*h/8 * (
x[0] +
3 * x[np.mod(np.arange(len(x)), 3) != 0].sum()+
2 * x[::3].sum() +
x[-1]
)
)
#Output: 1.462654874404461

Return n-th term of a mathematical sequence

I want to create a def that you provide a positive integer n and a number x, and it returns the n-th term of the following sequence:
x - x^3/3 + x^5/5 - x^7/7 + x^9/9 - x^11/11.....
where:
first term is: a1 = x
second term is : a2 = x - x^3/3
third term is: a3 = x - x^3/3 +x^5/5
etc
This is what i came up with, but it doesn't seem to return constistent results compared to calculating the values manually. Please, tell me if I'm missing something! Thank you very much!
def madh(n, x):
if n == 1:
return x
else:
result = (((-1)**n) * (x ** (2*n-1)) / (2*n - 1)) + madh((n - 1), x)
return result
Your mistake is in the sign of the element. For example, the second term is negative, but it is positive in your case ((-1) ** 2 = 1). So, the corrected version is:
def madh(n, x):
if n == 1:
return x
else:
# change n to (n+1) in the power of -1
result = (((-1)**(n+1)) * (x ** (2 * n - 1)) / (2 * n - 1)) + madh((n - 1), x)
return result
By the way, your function returns the sum of series up to n-th terms, not the n-th term of the series.
The nth term of the series is ((x^n)/n)*(-1^(n+1)). Simple function for that would be
def nth_num(n,x):
if n==1:
return x
return nth_num(n-1,x) + ((x**n)/n)*(-1**(n+1))

How can I use input function to fill the parameters?

Create a function called computepay which takes two parameters (hours and rate ).
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
This is my code, but it doesn't show an input dialog when I run the program.
def computepay(x, y):
x = input('Enter Hours: ')
y = input('Enter Rate: ')
if int(x) <= 40 :
print('\nPay: ' + int(x) * int(y))
else :
print('\nPay: ' + 40 * int(y) + ((int(x) - 40) * 15))
If you want to just call the function with zero or empty string or even you can pre define in it, now you can get the input dialog in whatever ide you are using
def computepay(x=0, y=0):
x = input('Enter Hours: ')
y = input('Enter Rate: ')
if int(x) <= 40 :
print('\nPay: ' + str(int(x) * int(y)))
else :
print('\nPay: ' +str( 40 * int(y) + ((int(x) - 40) * 15)))
computepay()
Do like this and let me know if that works out for you Dale
def computepay():
x = int(input('Enter Hours: ')) #this is the way to get int input
y = int(input('Enter Rate: '))
if x <= 40 :
basicCompute = x * y
#use f-string instead, it is clean and correct, the way you were doing things with the print was wrong
print(f'\nPay: {basicCompute}')
else :
# have a variable which computes that for you, don't do that in your print directly
compute = (40 * y) + ((x - 40) * 15)
print(f'\nPay: {compute}')
# this is how you call your method
computepay()
OUTPUT
# this is how you get the thing in your terminal, tested and verified
Enter Hours: 30
Enter Rate: 10
Pay: 300
ALTERNATIVE
If you want your method to accept the two arguments, then do not do input() inside your method
def computepay(x, y):
# use x and ye with the arguments only
if x <= 40 :
basicCompute = x * y
print(f'\nPay: {basicCompute}')
else :
compute = (40 * y) + ((x - 40) * 15)
print(f'\nPay: {compute}')
# When you call your method, before that you have to accept x and y params, then
# pass it to your method
hours = int(input('Enter Hours: '))
rate = int(input('Enter Rate: '))
# then pass it to your method
# this will do the call, and print the data in your console
computepay(hours, rate)
Hope that helps :)
You need to call that function below.
computepay(parameterA,parameterB)
Mind the indentation issues!

I want to add two extremely large numbers in python which even bignum can't handle

I am new in python,I want to add two extremely large numbers in python which even bignum can't handle. I can take these two numbers as a string and then can calculate from the end and as like we used to do in old school addition process. we can take the carriage and add it to the next numbers and so on.
Please assist.
The question seemed interesting enough for a Christmas Day coding snack.
Here's my implementation using many of the builtins in Python.
reversed is used to iterate over the digit sequences from right to left, i.e. like we would when computing on paper
zip_longest "fills" in the sequences' ends with zeroes (as we would ignore digits on paper)
divmod computes the carried-forward value and the current digit in a single call.
The result is reversed, so it's once more reversed to be least-significant-digit-last, and stray zeroes on the left are removed using lstrip.
It does not handle negative numbers, though.
from itertools import zip_longest
def add(a, b):
out = []
a = [int(c) for c in str(a)]
b = [int(c) for c in str(b)]
carry = 0
for ca, cb in zip_longest(reversed(a), reversed(b), fillvalue=0):
carry, digit = divmod(ca + cb + carry, 10)
out.append(str(digit))
return "".join(reversed(out)).lstrip("0")
a = 9999 ** 29
b = 3725241 ** 9
assert add(a, b) == str(a + b)
I achieved that after 3 hours of work. :)
def add_func(num1,num2):
res_list = []
number1 = str(num1)
number2 = str(num2)
length1 = len(str(number1))
length2 = len(str(number2))
if(length1 > length2):
while(length1 > length2):
number2 = '0' + number2
length2 += 1
if(length2 > length1):
while(length2 > length1):
number1 = '0' + number1
length1 += 1
i = max(length1,length2)
carry = 0
while(i > 0):
if(int(number1[i-1]) + int(number2[i-1]) + carry > 9):
result = str(int(number1[i-1]) + int(number2[i-1]) + carry)
res_list.insert(0,(result[-1]))
carry = 1
if(i==1):
result = str(int(number1[i-1]) + int(number2[i-1]) + carry)
res_list[0]= result
elif(int(number1[i-1]) + int(number2[i-1]) > 9):
result = str(int(number1[i-1]) + int(number2[i-1]))
res_list.insert(0,(result[-1]))
carry = 1
else:
result = str(int(number1[i-1]) + int(number2[i-1]) + carry)
res_list.insert(0,(result[-1]))
carry = 0
i -=1
final_output = ('').join(res_list)
return final_output
print(add_func(9999**29,3725241**9))

How to write cos(1)

I need to find a way to write cos(1) in python using a while loop. But i cant use any math functions. Can someone help me out?
for example I also had to write the value of exp(1) and I was able to do it by writing:
count = 1
term = 1
expTotal = 0
xx = 1
while abs(term) > 1e-20:
print("%1d %22.17e" % (count, term))
expTotal = expTotal + term
term=term * xx/(count)
count+=1
I amm completely lost as for how to do this with the cos and sin values though.
Just change your expression to compute the term to:
term = term * (-1 * x * x)/( (2*count) * ((2*count)-1) )
Multiplying the count by 2 could be changed to increment the count by 2, so here is your copypasta:
import math
def cos(x):
cosTotal = 1
count = 2
term = 1
x=float(x)
while abs(term) > 1e-20:
term *= (-x * x)/( count * (count-1) )
cosTotal += term
count += 2
print("%1d %22.17e" % (count, term))
return cosTotal
print( cos(1) )
print( math.cos(1) )
You can calculate cos(1) by using the Taylor expansion of this function:
You can find more details on Wikipedia, see an implementation below:
import math
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
def cos(order):
a = 0
for i in range(0, order):
a += ((-1)**i)/(factorial(2*i)*1.0)
return a
print cos(10)
print math.cos(1)
This gives as output:
0.540302305868
0.540302305868
EDIT: Apparently the cosine is implemented in hardware using the CORDIC algorithm that uses a lookup table to calculate atan. See below a Python implementation of the CORDIS algorithm based on this Google group question:
#atans = [math.atan(2.0**(-i)) for i in range(0,40)]
atans =[0.7853981633974483, 0.4636476090008061, 0.24497866312686414, 0.12435499454676144, 0.06241880999595735, 0.031239833430268277, 0.015623728620476831, 0.007812341060101111, 0.0039062301319669718, 0.0019531225164788188, 0.0009765621895593195, 0.0004882812111948983, 0.00024414062014936177, 0.00012207031189367021, 6.103515617420877e-05, 3.0517578115526096e-05, 1.5258789061315762e-05, 7.62939453110197e-06, 3.814697265606496e-06, 1.907348632810187e-06, 9.536743164059608e-07, 4.7683715820308884e-07, 2.3841857910155797e-07, 1.1920928955078068e-07, 5.960464477539055e-08, 2.9802322387695303e-08, 1.4901161193847655e-08, 7.450580596923828e-09, 3.725290298461914e-09, 1.862645149230957e-09, 9.313225746154785e-10, 4.656612873077393e-10, 2.3283064365386963e-10, 1.1641532182693481e-10, 5.820766091346741e-11, 2.9103830456733704e-11, 1.4551915228366852e-11, 7.275957614183426e-12, 3.637978807091713e-12, 1.8189894035458565e-12]
def cosine_sine_cordic(beta,N=40):
# in hardware, put this in a table.
def K_vals(n):
K = []
acc = 1.0
for i in range(0, n):
acc = acc * (1.0/(1 + 2.0**(-2*i))**0.5)
K.append(acc)
return K
#K = K_vals(N)
K = 0.6072529350088812561694
x = 1
y = 0
for i in range(0,N):
d = 1.0
if beta < 0:
d = -1.0
(x,y) = (x - (d*(2.0**(-i))*y), (d*(2.0**(-i))*x) + y)
# in hardware put the atan values in a table
beta = beta - (d*atans[i])
return (K*x, K*y)
if __name__ == '__main__':
beta = 1
cos_val, sin_val = cosine_sine_cordic(beta)
print "Actual cos: " + str(math.cos(beta))
print "Cordic cos: " + str(cos_val)
This gives as output:
Actual cos: 0.540302305868
Cordic cos: 0.540302305869

Resources