what is my best approach to deal with negative floating values in Python3? I know I can remove the negative all together with strip but I'd like to return the negative result if possible

Example the following code returns a math domain error due to the negative number:

eps = -2.1
bps = 5

def calc_grahamNum(self):    
    ''' Graham Number Calculator '''    
    grahamNum = round(float(math.sqrt(22.5 * eps * bps)),2)
    return grahamNum

Edited 8 Months Ago by steven.rose.94: spelling

I found cmath as well which isn't working as I had hoped either. It throws the error :
TypeError: can't convert complex to float

import cmath 

eps = -2.1
bps = 5

def calc_grahamNum(self):
    ''' Graham Number Calculator '''
    grahamNum = round(float(cmath.sqrt(22.5 * eps * bps)), 2)
    return grahamNum

not exactly, though that would be great if I could see the result as a negative somehow. I am scraping information from Yahoo converyting it to a float then taking the square root of those numbers, normally the numbers are postive so it works well. Unfortunatly when I get a negative number the entire sequence stops, so I am really asking how to throw an error for the negative number and still continue on with the rest of the program as it stops all the calculations beyond that point. I'm a very new programmer with no formal education in this stuff just learning from books and youtube, I've been thinking of trying some sort of an if / else statement but I dont understand how to implement it if I receive an error and still have the program continue to the next step. if it helps this is the full code I have to this point.

https://github.com/PtahX/TSX.py/blob/master/StockChecker1.0.py

Edited 8 Months Ago by steven.rose.94

I'm using your code above and it is exactly what you are doing. The code should fault if you put a negative number in that function.

There are tomes on the web about square root of negative numbers so that's not "programming" but math.

Maybe you should test if the number you will square root is negative and handle it as you wish.

You could just ignore the error data by try.. except.

self is not good name for regular parameter as it is normally used in oo programs for the instance itself.

Tony

Edited 8 Months Ago by pyTony

Comments
Good idea about the "self" variable.

You could use nan

from math import sqrt
nan = float('nan')
def mysqrt(x):
    return sqrt(x) if x >= 0.0 else nan

See https://en.wikipedia.org/wiki/NaN

Edit: Hi Tony! It's been a while...
Edit2: numpy.sqrt() already returns nan for negative numbers!
Edit3: please @steven.rose.94, use python tag as well as python3 to increase the audience of your posts.

Edited 8 Months Ago by Gribouillis

This question has already been answered. Start a new discussion instead.