简体   繁体   中英

How to sqrt a number and if its a decimal, give a different output

I'm trying to write some python code where it performs a sqrt on a give number. Realizing that some situations might simply spit out a decimal (which I don't want). How do I check or what code should I add to determine whether the result is a whole number or a decimal in the code before it decides what to do with it?

This question is different as it is not a list and that question was how to do so in a list, not how to ensure the accuracy of the square root function.

Why don't you check if int(num) == num: . That should work.

from decimal import *
getcontext().prec = 20 #It represents the precision. Increase it if you need.
num = Decimal(num).sqrt()
if int(num) == num:
    print 'whole number'
else:
    pass

Would a conditional such as that found below suffice?

import math

def alternativeSqrt(x):
    num  = x**0.5
    if math.floor(num) == num:
        return num
    else:
        return f(x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM