def GetE(x1, x2, k, x, z, N):
firstHeight = math.exp(((k/(2*math.pi*z)) * ((x-x1) ** 2))j)
My function gives me a syntax error on the line defining firstHeight. I believe it is to do with not being able to define a complex number with variables, as I have tried:
test = 2 + (k)j
and also recieved a syntax error. Does anyone know how to fix this?
math does not support complex numbers, for that you have cmath:
import math, cmath
cmath.exp(((k/(2*math.pi*z)) * ((x-x1) ** 2))*1j)
# (0.998966288513345+0.045457171204028084j)
Or you could use NumPy:
np.exp(((k/(2*np.pi*z)) * ((x-x1) ** 2))*1j)
#(0.998966288513345+0.045457171204028084j)
That, and also as #GreenCloakGuy points out, you can't use j to convert a non-literal into a complex number. You can instead use complex() or 1j
The j suffix can only be used in an imaginary literal, not with variables. To get a negative imaginary number from a variable, multiply the variable by -1j.
firstHeight = math.exp(((k/(2*math.pi*z)) * ((x-x1) ** 2)) * -1j)
test = 2 + k * -1j
Related
The question is:
How do I verify that sin^2(x) + cos^2(x) = 1 for 𝑥=𝜋,𝜋/2,𝜋/4,𝜋/6?
I have no idea on how to approach this problem
Please Help!
Any help would be greatly appreciated
First, ^ in python is bitwise XOR. To raise x to the y power, you do x ** y. To do math operations like sin and cos, you would use the builtin math module. Lastly, to check if a value is equal to another value, you use ==. So checking what you wrote out would look like this:
import math
x = math.pi
print(math.sin(x) ** 2 + math.cos(x) ** 2 == 1)
I'm working in somewhat of a limited development environment. I'm writing a neural network in Python. I don't have access to numpy and as it is I can't even import the math module. So my options are limited. I need to calculate the sigmoid function, however I'm not sure how the exp() function works under the hood. I understand exponents and that I can use code like:
base = .57
exp = base ** exponent
However I'm not sure what exponent should be? How do functions like numpy.exp() calculate the exponent? This is what I need to replicate.
The exponential function exp(a) is equivalent to e ** a, where e is Euler's number.
>>> e = 2.718281828459045
>>> def exp(a):
... return e ** a
...
>>> import math # accuracy test
>>> [math.exp(i) - exp(i) for i in range(1, 12, 3)]
[0.0, 7.105427357601002e-15, 2.2737367544323206e-13, 1.4551915228366852e-11]
def sigmoid(z):
e = 2.718281828459
return 1.0/(1.0 + e**(-1.0*z))
# This is the formula for sigmoid in pure python
# where z = hypothesis. You have to find the value of hypothesis
you can use ** just fine for your use case it will work with both float and integer input
print(2**3)
8
print(2**0.5 )
1.4142135623730951
if you really need a drop in replacement for numpy.exp()
you can just make a function that behaves like it is written in the docs https://numpy.org/doc/stable/reference/generated/numpy.exp.html
from typing import List
def not_numpy_exp(x:[List[float],float]):
e = 2.718281828459045 # close enough
if type(x) == list:
return [e ** _x for _x in x]
else:
return e**x
how the exp() function works under the hood
If you mean math.exp from built-in module math in this place it does simply
exp(x, /)
Return e raised to the power of x.
where e should be understand as math.e (2.718281828459045). If import math is not allowed you might do
pow(2.718281828459045, x)
instead of exp(x)
I have the following calculation for sympy:
import sympy
q, r = sympy.symbols("q r")
equation = (((-q + r) - (q - r)) <= 0).simplify()
print(equation) # q >= r
equation = ((sympy.sqrt(2) * (-q + r) - sympy.sqrt(2) * (q - r)) <= 0).simplify()
print(equation) # q <= r
I don't see why the results should differ. What am I missing?
Edit
I am using version 1.5.1 of sympy and can see this on Python 3.6.6 and 3.7.7.
A fix for this is given here. It looks like gcd was assumed to behave like igcd (which gives a nonnegative value). But when dealing with non-integers, gcd currently can give a negative result, thus the error. So SymPy will either modify gcd and the simplify code will work or the simplification routine must account for the sign of the extracted gcd.
How to calculate in Python and without numpy the geometric mean of a list of numbers in a safe way, so I do avoid RuntimeWarning which this function produces sometimes:
data = [1,2,3,4,5]
result = reduce(mul, data) ** (1 / len(data))
I found out that i can use this log function to get the same result, but i have issue with log function not accepting negative values.
result = (1 / len(data)) * sum(list(map(math.log10, data)))
Can I map the data with abs function before map to log10?
Is there better way?
generally the n_th root of negative numbers are complex numbers
the code works with cmath base e log, exponentiation
from functools import reduce
import operator
from cmath import log, e
data = [1,2,3,4,5]
rmul = reduce(operator.mul, data) ** (1 / len(data))
rln = e**((1 / len(data)) * sum(list(map(log, data))))
rmul, rln
Out[95]: (2.605171084697352, (2.6051710846973517+0j))
data = [1,2,3,-4,5]
rmul = reduce(operator.mul, data) ** (1 / len(data))
rln = e**((1 / len(data)) * sum(list(map(log, data))))
rmul, rln
Out[96]:
((2.1076276807743737+1.531281143283889j),
(2.1076276807743732+1.5312811432838889j))
some checks:
abs(rln)
Out[97]: 2.6051710846973517
rln**5
Out[98]: (-120.00000000000003-1.4210854715202004e-14j)
for more fun and argument:
'the' square root of a positive valued a isn't singular, and positive, it is both the + and - signed values: +/- sqrt(a)
and 'the' square root of negative a is similarly both the +/- 1j * sqrt(a) values
Geometric means with negative numbers are not well-defined. There are several workarounds available which depend on your application. Please see this and also this paper. The main points are:
When all the numbers are negative you may be able to define a geometric mean by temporarily suspending the signs, take geometric mean and add them back.
If you have mix of positive and negative numbers and if odd number of them are negative then the geometric means become undefined. In any case because you're ignoring the signs the result is not meaningfule
It may be possible to separately evaluate the positive and negative parts calculate the means and them combine them with some weights as the paper does but the accuracy will depend on various factors (also described).
In terms of the code I do not get a Runtime error (see code below). If you can show an example of your code I can try to reproduce that and update my answer. And yes you cannot pass negative values to log so you have to take the absolute values where appropriate (as described above). Note that with python 2 you have to either import division from __future__() module or use a floating point number when taking fractional power otherwise you'll get wrong result.
>>> data = [1,2,3,4,5]
>>> import operator
>>> result = reduce(operator.mul, data) ** (1 / len(data))
>>> result
1
>>> result = reduce(operator.mul, data) ** (1.0 / len(data))
>>> result
2.605171084697352
i wrote this python code, which from wolfram alpha says that its supposed to return the factorial of any positive value (i probably messed up somewhere), integer or not:
from math import *
def double_factorial(n):
if int(n) == n:
n = int(n)
if [0,1].__contains__(n):
return 1
a = (n&1) + 2
b = 1
while a<=n:
b*=a
a+= 2
return float(b)
else:
return factorials(n/2) * 2**(n/2) *(pi/2)**(.25 *(-1+cos(n * pi)))
def factorials(n):
return pi**(.5 * sin(n*pi)**2) * 2**(-n + .25 * (-1 + cos(2*n*pi))) * double_factorial(2*n)
the problem is , say i input pi to 6 decimal places. 2*n will not become a float with 0 as its decimals any time soon, so the equation turns out to be
pi**(.5 * sin(n*pi)**2) * 2**(-n + .25 * (-1 + cos(2*n*pi))) * double_factorial(loop(loop(loop(...)))))
how would i stop the recursion and still get the answer?
ive had suggestions to add an index to the definitions or something, but the problem is, if the code stops when it reaches an index, there is still no answer to put back into the previous "nests" or whatever you call them
You defined f in terms of g and g in terms of f. But you don't just have a circular definition with no base point to start the recursion. You have something worse. The definition of f is actually the definition of g inverted. f is precisely undoing what g did and vice versa. If you're trying to implement gamma yourself (ie. not using the one that's already there in the libraries) then you need to use a formula that expresses gamma in terms of something else that you know how to evaluate. Just using one formula and its inversion like that is a method that will fail for almost any problem you apply it to.
In your code, you define double_factorial like
double_factorial(n) = factorial(n/2) * f(n) ... (1)
and in the factorial you define it as
factorial(n) = double_factorial(2*n) / f(2*n) ... (2)
which is equivalent to equation (1), so you created a circular reference without an exit point. Even math can't help. You have to define either factorial or double_factorial, e.g.
def factorials(n):
return tgamma(n + 1)