When running this code it is giving me this error:
x = p((1/2) - (2/q)) TypeError: 'int' object is not callable
p = 0
q = 0
while (p==0):
p = int(input("Enter an integer for p: "))
while (q==0):
q = int(input("Enter an integer for q: "))
x = p((1/2) - (2/q))
print(x)
You didn't use *, the multiplication operator:
x = p * ((1/2) - (2/q))
------^ here
In math equations, the multiplication operator is often left out. E.g. a(b-2) means "a times the quantity b-2).
In programming however, you must explicitly include the multiplication operator. E.g. a*(b-2).
In Python (and most other languages), when a token is followed by open/close parenthesis, it implies that a function is being called. This is why you received the 'int' object is not callable error; because p is an int, and it looked like you were trying to call it.
You have another problem in your translation from "equation" to Python. In Python 2, integer division is used (when both operands are integers, of course). Which means that this term:
x = p * ((1/2) - (2/q))
^^^^^
is going to equal zero.
In Python 3, this is not the case. Division (with a single /) is always floating point.
Since this is probably not desired, you should do one of the following:
Convert one of the terms to float, e.g. float(1)/2
from __future__ import division which enables the Python 3 behavior
Just replace the term with 0.5
Because you are trying to do something like this:
p()
but p is variable.
Related
I'm writing a programme that converts complex numbers.
Right now I'm having problems with this piece of code:
import numpy
complexnr = 1+1j
mod= numpy.absolute(complexnr)
print(mod)
The output of this code is:
1.4142135623730951
I would like to get √2 as the output.
I have been advised to use the sympy module but I have had no luck with this either. What would be the easiest way to get this result?
EDIT
input_list = ["Enter your complex number (a+bi): ", \
"Degrees or radians?", \
"To how many decimal places do you want to round the argument?"]
output = multenterbox(text, title, input_list)
algebraline = output[0]
choice = output[1]
round2 = int(output[2])
#converting complex number to a suitable form for numpy
if "i" in algebraline:
j = algebraline.replace("i","j")
indeks = algebraline.index("i")
list = []
for element in algebraline:
list.append(element)
if "i" in algebraline and algebraline[indeks-1]=="+" or algebraline[indeks-1]=="-":
list.insert(indeks, 1)
x = "".join(str(e) for e in list)
j = x.replace("i","j")
arv = eval(j)
elif "i" not in algebraline:
arv = eval(algebraline)
#let's find the module
a = int(list[0])
b = int(list[2])
module = sqrt(a**2+b**2)
this method works well when the complex number is 1+i for example, however when i try to insert sqrt(3)-1i, the list looks like this ['s', 'q', 'r', 't', '(', '3', ')', '-', 1, 'i'] and my programme won't work. Same problem occurs when b is a root (for example 1-sqrt(3)i). What can be done to make it work for square roots as well? (I need numpy later on to calculate angles, that's why converting 'i' into 'j' is important)
Works by using
I (from sympy) rather than 1j
builtin abs function which calls sympby.Abs for complex arguments
Code
from sympy import I
complexnr = 1 + I # use I rather than 1j
display(abs(complexnr)) # also works with np.abs and np.absolute
Output:
print(abs(complexnr))
Output: sqrt(2)
If you want to use SymPy, you have to write the complex numbers as sympy expressions.
from sympy import *
cabs = lambda z: sqrt(re(z)**2 + im(z)**2)
complexnr = 1 + 1j
print(cabs(complexnr))
# out: 1.4142135623731
We are getting a float number because complexnr is of type complex and its real and imaginary parts are of type float. Thus, SymPy's re and im functions returns float numbers. But when sqrt receives a float number, it evaluates the result.
We can workaround this problem in two ways.
The first: if we are dealing with simple complex numbers where real and imaginary parts are integers, we can write the complex number as a string, sympify it (which means convert to a sympy expression):
complexnr = sympify("1 + 1j")
print(cabs(complexnr))
# out: sqrt(2)
A second way consist in using the complex number directly, then apply nsimplify in order to attempt to convert the resulting float number to some symbolic form:
complexnr = 1 + 1j
result = cabs(complexnr) # result is a Float number, 1.4142135623731
print(result.nsimplify())
# out: sqrt(2)
I want to raise an integer x to the power of (p-1)/2 modulo p, where p is a prime number.
p and x are 1024 bit integers.
There is some theorem (consequence of Lagrange's theorem) which states that the result must be equal to 1, -1 or 0 mod p.
Consider the following code:
p = 101524035174539890485408575671085261788758965189060164484385690801466167356667036677932998889725476582421738788500738738503134356158197247473850273565349249573867251280253564698939768700489401960767007716413932851838937641880157263936985954881657889497583485535527613578457628399173971810541670838543309159139
x = 85256449776780591202928235662805033201684571648990042997557084658000067050672130152734911919581661523957075992761662315262685030115255938352540032297113615687815976039390537716707854569980516690246592112936796917504034711418465442893323439490171095447109457355598873230115172636184525449905022174536414781771
print(pow(x, int((p-1)/2), p))
with python 3.9.2 it gives
27980403064579636028055449870417771181244326459581529717454053960638629219169075321551780381136980928762710368915290204712290597582758394662971100864236376202143782193827974545206195986726913123604423878525492811925195928165327468926425839191512631291796118427230662866781350545453987781889400451930787015913
which is not -1 mod p.
With sagemaths, it gives 1, so probably the right result.
So obviously, there is something wrong here. I thought that python was able to handle arbitrary-length integers without any problem. Am I wrong ?
The problem is with the division operator /. Integers have arbitrary length, but floats don't. When you do int((p-1)/2), it's getting converted to float and then back to int, so the precision is lost. If you try integer division //:
pow(x, (p-1)//2, p)
it will work as expected.
What is the purpose of using int in the following code?
sum = sum + int(n % 10)
If n is an int, it does absolutely nothing, but if n is a float, it will make sure that the result of the modulo is always an integer.
Example:
>>> n = 3.14
>>> n % 10
3.14
>>> int(n % 10)
3
The actual reason why this was used and if it was necessary cannot be determined from only that one line in your question. But since that line also overrides the built-in sum and doesn't use the += compound assignment, it smells like a poor coder, so probably the usage of int() is just an unnecessary oversight.
It's also possible that n is an instance of some other class that implements __mod__ in a weird way, but that's quite inlikely.
I have a function that I've written out and would like to perform mathematical operations on it, the same way I can with numbers.
For instance, with the code below, I would like to take Sup(3) - Sup(2) = result, but this doesn't work. Can I take functions that I've defined and perform mathematical operations on them, the same way we can perform mathematical operations on numbers (i.g, 2 * 2 = 4)?
For n = 2, my result is 1.083
For n = 3, my result is 1.717 using the code below.
def Sup(n):
mylist = []
for n in range (2,2**n+1):
Su = (1/n)
mylist.append(Su)
#print(mylist)
print (sum(mylist))
When I attempt this operation, I get the following error:
---> 12 Sup(2)- Sup(3)
TypeError: unsupported operand type(s) for -: 'NoneType' and 'NoneType'neType'
What does this mean?
Can I take functions that I've defined and perform mathematical operations on them, the same way we can perform mathematical operations on numbers?
Yes you can, assuming that your functions return numbers.
What does this mean?
As pointed out in comments, it means that your function doesn´t return anything. Adding return to your function should do the trick:
def Sup(n):
mylist = []
for n in range (2,2**n+1):
Su = (1/n)
mylist.append(Su)
#print(mylist)
print (sum(mylist))
return sum(mylist)
I am trying to do integration in Python but whenever I key in a value my outputs always results in 0. What the reason?
E.g.:
def main():
eq_of_form()
value_of_a()
value_of_b()
value_of_c()
value_of_m()
value_of_n()
value_of_x()
area_under_graph()
def eq_of_form():
print "Eq of the form y = ax^m + bx^n + c " + ":"
def value_of_a():
return raw_input("Enter value for a \n")
def value_of_b():
return raw_input("Enter value for b \n")
def value_of_c():
return raw_input("Enter value for c \n")
def value_of_m():
return raw_input("Enter value for m \n")
def value_of_n():
return raw_input("Enter value for n \n")
def value_of_x():
return raw_input("Enter a value for x to find " +
"value of y and the gradient at that point \n " + "x = ")
def area_under_graph():
y = (int(value_of_a())*int(value_of_x())**(int(value_of_m())+1))/((int(value_of_m())+1))
// * 2nd part.This works for me(:
// + (int(value_of_b())) * (int(value_of_x())**
// (int(value_of_n())+1))/(int(value_of_n())+1) + ((int(value_of_c())*int(value_of_x())))
print y
main()
(* Note: the eq under the area_under_graph() function is only half of it because the other half kind of work so I did not post it:))
For the top code, I tried inputting the values here: (maybe you can try using the same(: )
a = 1
b = 2
c = 1
m = 2
n = 1
x = 1
I am supposed to get 7/3 which is 2.333, but I end up getting 2. The problem appears to lie in the first part of the eq.
Sorry for the newbie question.
Your code at the start is wrong. You need to assign your variables after you read the user input:
value_of_a()
should be:
a = value_of_a()
It is also unnecessary to write a separate function for inputting each variable. You could instead have a function that takes a parameter:
def get_user_value(name):
return raw_input("Enter value for %s\n" % name)
a = get_user_value("a")
b = get_user_value("b")
# etc..
But then you ignore all these values and read them again inside the area_under_curve() method. This is probably not what you intend to do. Furthermore inside this method you assume that all parameters are integers. If you are using Python 2.5 the division here is integer division:
m1/m2
This could return 0 when the result was actually supposed to be a non-integer like 0.125. You need to use floats instead of integers to do the calculation. You can do this in Python 2.5 using float(m). In Python 3.0 the division operator does what you want by default.
/ does Integer division in Python2, this means a/b is the biggest integer c with c*b <=a, so 7/3 is indeed 2. You want floats, so you need to use them .. replace all the int with float in your code.
You should probably take another look at functions too ... you code can be much much shorter :-)
In Python 2.x, dividing an integer by another integer results in an integer. Either use from __future__ import division, or turn one of the integers into a float by passing it to float().
The issue is that you're using integer arithmetic - see all those int calls you've got everywhere. Integer arithmetic (in Python 2.x) will only ever return integers, so you'll never get 2.33, only 2.
Use float() instead of int() and things should work.