user-defined Sigmoid function in python - python

I have one doubt on using user-defined sigmoid function(Logistic). I tried using numpy.exp & math.exp for the sigmoid formula (1 / 1+ e^-x).
1 / (1 + numpy.exp(-x))
1 / (1 + math.exp(-x))
Both methods gives the value 6.900207837141513e-36 for x = -80.96151181531121.
But, we are expecting a value between 0 & 1.
Am I missing anything?

6.900207837141513e-36 is scientific record for 0.00...06900207837141513 (I omitted 13 zeroes)
You can read it as "6.900... divided by 10^36". In this case you probably can treat value as 0.
See https://en.wikipedia.org/wiki/Scientific_notation#E_notation

>>> 6.900207837141513e-36 > 0
True

Note the e-36 on the end of 6.900207837141513e-36. This is equivalent to the scientific notation 6.900207837141513 * 10^-36. In other words, it is a very small value that is basically zero.

Related

Rounding coefficients of a symbolic expression in SymPy

I'm currently trying to calculate a negative group delay of analog filters by using symbolic calculations in Python. The problem that I'm currently trying to resolve is to get rid of some very small imaginary coefficients.
For example, consider fraction with such numerator (imaginary parts are bolded):
(-1.705768*w^18 + 14.702976409432*w^16 + 1.06581410364015e-14*I*w^15 - 28.7694094371724*w^14 - 9.94759830064144e-14*I*w^13 + 59.0191623753299*w^12 + 5.6843418860808e-14*I*w^11 + 24.7015297857594*w^10 - 1.13686837721616e-13*I*w^9 - 549.093511217598*w^8 - 5.6843418860808e-14*I*w^7 + 1345.40434657845*w^6 + 2.27373675443232e-13*I*w^5 - 1594.14046181284*w^4 - 1.13686837721616e-13*I*w^3 + 980.58940367608*w^2 - 254.8428594382)
Is there any way to automatically round those small coefficients, so they would be equal 0 (in general any negligligible values)? Or at least, can I somehow filter imaginary values out? I've tried to use re(given_fraction), but it couldn't return anything. Also standard rounding function can't cope with symbolic expressions.
The rounding part was already addressed in Printing the output rounded to 3 decimals in SymPy so I won't repeat my answer there, focusing instead of dropping imaginary parts of coefficients.
Method 1
You can simply do re(expr) where expr is your expression. But for this to work, w must be known to be a real variable; otherwise there is no way for SymPy to tell what the real part of (3+4*I)*w is. (SymPy symbols are assumed to be complex unless stated otherwise.) This will do the job:
w = symbols('w', real=True)
expr = # your formula
expr = re(expr)
Method 2
If for some reason you can't do the above... another, somewhat intrusive, way to drop the imaginary part of everything is to replace I with 0:
expr = expr.xreplace({I: 0})
This assumes the expression is already in the expanded form (as shown), so there is no (3+4*I)**2, for example; otherwise the result would be wrong.
Method 3
A more robust approach than 2, but specialized to polynomials:
expr = Poly([re(c) for c in Poly(expr, w).all_coeffs()], w).as_expr()
Here the expression is first turned into a polynomial in w (which is possible in your example, since it has a polynomial form). Then the real part of each coefficient is taken, and a polynomial is rebuilt from them. The final part as_expr() returns it back to expression form, if desired.
Either way, the output for your expression:
-1.705768*w**18 + 14.702976409432*w**16 - 28.7694094371724*w**14 + 59.0191623753299*w**12 + 24.7015297857594*w**10 - 549.093511217598*w**8 + 1345.40434657845*w**6 - 1594.14046181284*w**4 + 980.58940367608*w**2 - 254.8428594382

Python-How to do Algebraic Math with Exponents and Square Roots

so I am having issues trying to do basic math in Python. I can do basic math, but when I add in exponents, square roots, etc, I have errors with the IDE. How do I do this?
Here are a few of my problems that I am having issues with:
(n(n-1))/2)
(4)* pi * r ** 2=
(r(cos(a)**2) + r(sin(b))**2)**(.5)
((y**2) - (y**1))/((x**2) - (x**1))=
(n*(n-1))/2 should work if you have already given n a numeric value (e.g. n=2 or something). Your original expression has unbalanced parentheses (three closing parens and only two opening parens) and it is missing the multiplication sign (*) which is necessary in python, otherwise n(n-1) would be interpreted as the function n supplied with the input n-1, in which case you get a message like "TypeError: 'int' object is not callable", assuming you had previously defined n=2 or the like. It's telling you that the integer n cannot be called like a function, which is how it interprets n().
To get pi (3.14159...) in python, you should import the math package and then use math.pi like this:
import math
r = 2
x = 4*math.pi*r**2
You don't need parentheses around the 4. Parentheses are used for grouping, when you need operations to be done in a different order than the standard order of operations. You don't need the trailing equal sign (that's a syntax error).
In the third expression you are using implicit multiplication notation which is fine for pencil and paper but in python you need to use * every time you multiply. Also, you need to import the math package and then use math.sin and math.cos.
import math
a = 90
b = 45
x = (r*(math.cos(a)**2) + r*(math.sin(b))**2)**(.5)
There doesn't appear to be anything wrong with the last expression except the trailing = sign which should be removed. Store the result of this expression in a variable if you want to keep it for future use:
z = ((y**2) - (y**1))/((x**2) - (x**1))
If you just type the expression at the command line it will print the result immediately:
x = 3
y = 2
((y**2) - (y**1))/((x**2) - (x**1))
but if you are using this expression in a script you want to save the result in a variable so you can use it later or print it out or something:
z = ((y**2) - (y**1))/((x**2) - (x**1))
As was previously pointed out in the comments, x**1 is the same, mathematically, as x so it's not clear why you would want to write it this way, but it's not wrong.
You can use math.pow() or the simpler ** syntax:
There are two ways to complete basic maths equations in python either:
use the ** syntax. e.g:
>>> 2 ** 4
16
>>> 3 ** 3
27
or use math.pow(). e.g:
>>> import math
>>> math.pow(5, 2)
25.0
>>> math.pow(36, 0.5)
6.0
As you can see, with both of these functions you can use any real power so negative for inverse or decimals for roots.
In general, for these types of equations, you want to look into the math module. It has lost of useful functions and defined constants that you may find useful. In particular for your specific problems: math.pi and these trig. functions.
I hope these examples and the links I made are useful for you :)

Python undesirable complex numbers [duplicate]

This question already has answers here:
Wrong value for cube root in Python
(3 answers)
Closed 5 years ago.
>>> a = -27
>>> a ** (1/3)
(1.5000000000000004+2.598076211353316j)
>>> -27 ** (1/3)
-3.0
I have to raise numbers of the list to a power 1/3 but when the number is negative I get a complex number. Why is there such difference in results of these two operations and how can I avoid the first one?
When you set a=-27, you are assigning the negative to the value as well. When you just type in -27**(1/3) it computes the exponent first and then the negative sign. This may be the reason for your issue.
A complex number z has 3 roots of z**3 so for z**(1/3) it's necessary to pick one. A conventional choice is the so-called principal value of z**(1/3) which has the least argument (i.e. it is the one which has the smallest angle with respect to the positive real axis). As you have found, that has nonzero imaginary part when z is a negative real number.
My advice is to just have a test such as if (z < 0): -((-z)**(1/3)) else: z**(1/3) (sorry if I got the wrong syntax).
You have a problem with your order of operations; power has precedence over unary minus.
-27 ** (1/3)
evaluates as
- (27 ** (1/3))
not as
(-27) ** (1/3) # gives a complex result
If a is negative, to get a real root, you need to do
-(-a)**(1/3)

Avoiding division by zero error in a function with cancelling variables

def nu(r):
'''Returns the stellar density function.'''
return 1 / ( r * (1 + (r / a))**3)
mass_int = lambda r: 4 * r**2 * nu(r)
print(mass_int(0))
This gives me a divide by zero error, presumably because of the 1/r term being evaluated in isolation. Is using sympy to form the correct algebraic expression the only way around this? Seems absurd.
It's not doing anything wrong. Given r = 0:
1 / ( r * (1 + (r / a))**3)
= 1 / ( 0 * (1 + (0 / a))**3)
= 1 / ( 0 * (1 + 0 )**3)
= 1 / ( 0 * 1 **3)
= 1 / ( 0 * 1 )
= 1 / 0
So when you ask for nu(0) you get an error. It doesn't look ahead and do special algebra things, it just throws the error. Python is not magic, it's not absurd that you'd need sympy for this.
I suggest you just add a special case to mass_int for r == 0.
This isn't a python question, or even a computer programming question. It's simple math.
f(x) = 1 / (x * (1 + x/a)**3)
g(x) = 4x**2
h(x) = 4x / (1 + x/a)**3
Is there a difference between f(g(r)) and h(r)? Of course there is. Even though the plots look exactly the same, f(g(0)) is undefined, and on a plot must show as a point discontinuity.
As an intelligent user of this function, you can recognize that the point discontinuity is there. If you choose, you can replace f(g(r)) with h(r). The only difference will be the desired one of having the function defined at 0.
Math doesn't do that on its own, and no programming language will reduce the function composition for you on its own, unless you ask it to, because you are the user, and you're supposed to know what you want from a program. If you create a function composition that has a point discontinuity, it's expected that you did so for a reason. The intelligence is expected to be in the programmer, not in the compiler. Either compose and reduce the function by yourself, or do something like having sympy do it. Either way, it's up to you to make it explicit to the computer that these two functions should be related to each other.

Strange behaviour when raising numbers to the power of zero in Python [duplicate]

This question already has answers here:
Calculation error with pow operator
(4 answers)
Closed 4 years ago.
I am using Python 2.7.5. When raising an int to the power of zero you would expect to see either -1 or 1 depending on whether the numerator was positive or negative.
Typing directly into the python interpreter yields the following:
>>> -2418**0
-1
This is the correct answer. However when I type this into the same interpretter:
>>> result = -2481
>>> result**0
1
the answer is 1 instead of -1. Using the complex builtin as suggested here has no effect on the outcome.
Why is this happening?
Why would you expect it to be -1? 1 is (according to the definition I was taught) the correct answer.
The first gives the incorrect answer due to operator precedence.
(-1)**0 = 1
-1**0 = -(1**0) = -(1) = -1
See Wikipedia for the definition of the 0 exponent: http://en.wikipedia.org/wiki/Exponentiation#Zero_exponent
-2418**0 is interpreted (mathematically) as -1 * (2418**0) so the answer is -1 * 1 = -1. Exponentiation happens before multiplication.
In your second example you bind the variable result to -1. The next line takes the variable result and raises it to the power of 0 so you get 1. In other words you're doing (-1)**0.
n**0 is 1 for any real number n... except 0: technically 0**0 is undefined, although Python will still return 0**0 == 1.
Your maths is wrong. (-2481)**0 should be 1.
According to wikipedia, Any nonzero number raised by the exponent 0 is 1.

Categories