Tanmay Jain
Tanmay Jain

Reputation: 123

How to apply log on negative values based upon some conditions in python

I know that we can't calculate negative value in log. I use math.log(number) to calculate log of any positive number.

I want to calculate the value of any number (let's say X) based upon the following conditions.

enter image description here

What is the efficient way to find any value for any number X (including negative, positive, and 0) based upon the above conditions in Python?

Thanks

Upvotes: 1

Views: 3422

Answers (2)

Alexandros Kyriakakis
Alexandros Kyriakakis

Reputation: 21

Try the following:

import math
def my_log(x):
    abs_x = abs(x)
    return ( (x//abs_x) * math.log(abs_x) if (x) else x)

Upvotes: 1

spacecraft1013
spacecraft1013

Reputation: 101

You can use multiple if statements to find the state of the variable you want to take the log of, then run the log based on the state of the variable:

def findlog(x):
    if x > 0:
        log = math.log(x)
    elif x < 0:
        log = math.log(x*-1)*-1
    elif x == 0:
        log = 0
    return log

Upvotes: 2

Related Questions