How to write a complex number in python? Indeed I have:
import math
a=3
b=4
function=a*j*x+b*y
I don't want to write directly 3j in my function since I absolutely want to use a, so how to convert a into a complex number? Cause in matlab it works when printing :
a=3
b=a*i
The result will gave: 0 + 3.0000i
Thank you for your answers.
j alone is a variable, you can have the complex number by typing 1j
>>> type(j)
NameError: name 'j' is not defined
>>> type(1j)
<type 'complex'>
So your code can be written as a function as
def function(x, y):
a = 3
b = 4
return a*1j*x+b*y
You can use the complex function to create a complex number from variables:
>>> a = 3
>>> b = 4
>>> complex(a, b)
(3+4j)
You can simply use Python's Built in complex() function
>>> first_number = 10
>>> second_number = 15
>>> complex(first_number, second_number)
(10+15j)
Related
This question already has answers here:
Construct callable function from string [duplicate]
(3 answers)
Closed 12 months ago.
I have four subroutines to multiply, divide, add and subtract 2 numbers which I will ask the user for.
My unfinished code is:
def multiply(a, b):
print(f"{a} x {b} = {a*b}")
def divide(a, b):
print(f"{a} รท {b} = {a*b}")
num1 = int(input("What is the first number?\n"))
num2 = int(input("What is the second number?\n"))
calculation = input("What calculation would you like to perform? [multiply, divide]\n")
calculation(num1, num2)
but it gives TypeError: 'str' object is not callable
Is it necessary to use if statements like:
if calculation == 'multiply':
multiply()
elif calculation == 'divide':
divide()
for all four subroutines or can I use the variable calculation to substitute for the function name.
Use a dictionary to hold your functions
funcs = {'multiply': multiply, 'divide': divide}
and then access funcs[calculation].
... or if you have a DRY fetish:
funcs = {f.__name__: f for f in [multiply, divide]}
Demo:
>>> funcs['multiply'](3, 4)
3 x 4 = 12
You could also access the globals() dict
>>> globals()['multiply'](3, 4)
3 x 4 = 12
but this is not such a good idea because the function to call comes from user input and who knows what weird callables are in globals().
Bonus: safeguarding against bad input
from functools import partial
def notfound(fname, *_, **__):
print(f'function {fname!r} not found')
Usage:
>>> calculation = 'multiply'
>>> funcs.get(calculation, partial(notfound, calculation))(3, 4)
3 x 4 = 12
>>> calculation = 'none'
>>> funcs.get(calculation, partial(notfound, calculation))(3, 4)
function 'none' not found
I use sympy (ver1.9).
I calculate the following expressions((1)~(4)) by sympy.simplify().
All of them are expected to be identical to 1 analytically.
but (4) did not return 1, and the expression isn't simplified.
Why does this happen?
Try rewriting to exp and then simplifying:
>>> eq=tanh(x-y)**2 + sech(x-y)**2
>>> eq.rewrite(exp).simplify()
1
or use the function to rewrite hyperbolics to trigonometric functions before simplifying, e.g. with fu:
>>> from sympy.simplify.fu import hyper_as_trig
>>> e,f=hyper_as_trig(eq)
>>> f(fu(e))
1
See also hyper_as_trig in simplify/fu.py.
If I write x=5+j in python3. It shows me type(x) is an int. why this
not considered as a complex number?
You forgot write number before j if you write 5+1j and check type you get what you want (complex type), like below:
x = 5+1j
type(x)
#complex
For define complex numbers you can use different approaches.
You can use np.complex like below:
import numpy as np
x = np.complex(5,1)
type(x)
# complex
print(x)
# (5+1j)
Also You can use cmath:
import cmath
x = complex(5,1)
type(x)
# complex
print(x)
# (5+1j)
You could use the cmath module which allows you to work with complex numbers.
A very simple example of usage:
import cmath
x = 5 + 1*1j
# alternatively
# x = complex(5,1)
print(type(x))
print(x)
Check out more: https://docs.python.org/3/library/cmath.html
It's a standard package, so you don't have to install anything.
The fact that type(x) is int probably means that you already have a variable j in your code, and that variable is an int. Just like this:
>>> j = 10
>>> x = 5 + j
>>> type(x)
<class 'int'>
Now, if you wish to create a complex number, you may either use the built-in complex function:
>>> x = complex(5, 1)
>>> x
(5+1j)
>>> type(x)
<class 'complex'>
or write a literal complex number:
>>> x = 5 + 1j
>>> x
(5+1j)
>>> type(x)
<class 'complex'>
The main difference between this and what you wrote is that 5 + j means "5 plus a variable called j", whereas 5 + 1j means "5 plus the complex number 1j". Remember that j is not the imaginary unit, it is the name of a variable. If you wish to write a complex literal, you need to write something like <number>j. In particular, the imaginary unit can be written as 1j.
This question already has answers here:
How do I get a decimal value when using the division operator in Python?
(13 answers)
Closed 8 years ago.
this is my code:
def pmi(w1,w2):
x = float(1)
x = (bg_fdist[(w1, w2)])/(f_brown[(w1)]*f_brown[(w2)])
print x
the values entered will be:
>>> bg_fdist[('of','the')]
9781
>>> f_brown[('of')]
36412
>>> f_brown[('the')]
6997`
so i expect my x to be very small and between 0 and 1.
but i get as a return:
>>>> pmi('of','the')
0
i assume that might be, because x gets still handled as an integer? why is this? can anyone point out how i might get my expected result?
greetings!
The x that you have declared as float(1) has nothing whatsoever to do with the result of the calculation in the second line: it was simply thrown away and replaced with the result from there. Instead, you'll need to explicitly case some of the elements of that calculation to floats.
The whole thing could be made clearer by splitting it up, like this:
def pmi(w1,w2):
first = float(bg_fdist[(w1, w2)])
second = float(f_brown[(w1)]*f_brown[(w2)])
result = first/second
return result
If you do
>>> x = float(1)
>>> x
1.0
>>> type(x)
<type 'float'>
x is indeed a float. But if after you instanciate it with an int, it's not a float anymore:
>>> x = 2
>>> x
2
>>> type(x)
<type 'int'>
When doing your division, you are using integer so:
>>> x = 2/4
>>> x
0
>>> type(x)
<type 'int'>
You still have an integer. Instead you could use float on your variable in your equation:
>>> x = float(2)/4
>>> x
0.5
You could also use from __future__ import division.
The current division (/) operator has an ambiguous meaning for
numerical arguments: it returns the floor of the mathematical
result of division if the arguments are ints or longs, but it
returns a reasonable approximation of the division result if the
arguments are floats or complex.
See: PEP 238
I need a calculate below expression using sympy in python?
exp = '(a+b)*40-(c-a)/0.5'
In a=6, b=5, c=2 this case how to calculate expression using sympy in python? Please help me.
The documentation is here: http://docs.sympy.org/. You should really read it!
To "calculate" your expression, write something like this:
from sympy import Symbol
a = Symbol("a")
b = Symbol("b")
c = Symbol("c")
exp = (a+b)*40-(c-a)/0.5
And that's it. If you meant something else by "calculate", you could also solve exp = 0:
sympy.solve(exp)
> {a: [0.0476190476190476*c - 0.952380952380952*b],
> b: [0.05*c - 1.05*a],
> c: [20.0*b + 21.0*a]}
For everything else, you should really read the docs. Maybe start here: http://docs.sympy.org/0.7.1/tutorial.html#tutorial
UPDATE: since you added the values for a, b, c to the question, you can add this to the solution:
exp.evalf(subs={a:6, b:5, c:2})
You can convert your string into a sympy expression using the parse_expr() function in the module sympy.parsing.sympy_parser.
>>> from sympy.abc import a, b, c
>>> from sympy.parsing.sympy_parser import parse_expr
>>> sympy_exp = parse_expr('(a+b)*40-(c-a)/0.5')
>>> sympy_exp.evalf(subs={a:6, b:5, c:2})
448.000000000000
I realise this was already answered above, but in the case of getting a string expression with unknown symbols and needing access to those symbols, here is the code I used
# sympy.S is a shortcut to sympify
from sympy import S, Symbol
# load the string as an expression
expression = S('avar**2 + 3 * (anothervar / athirdvar)')
# get the symbols from the expression and convert to a list
# all_symbols = ['avar', 'anothervar', 'athirdvar']
all_symbols = [str(x) for x in expression.atoms(Symbol)]
# do something with the symbols to get them into a dictionary of values
# then we can find the result. e.g.
# symbol_vals = {'avar': 1, 'anothervar': 2, 'athirdvar': 99}
result = expression.subs(symbols_vals)
Well, I know that eval is evil, but if you have a,b and c defined in your program, and you can make sure that it's safe to do the eval, you don't need sympy.
>>> a=5
>>> b=5
>>> c=2
>>> exp = '(a+b)*40-(c-a)/0.5'
>>> eval(exp)
406.0
>>> a, b, c = sympy.symbols('a b c')
>>> exp = (a + b) * 40 - (c - a) / 0.5
>>> exp.evalf(6, subs={a:6, b:5, c:2})
448.000