首页 > 解决方案 > 如何在 Python 中找到负数的 sqrt

问题描述

当我输入一个负数时,它会给我 NaN(不是数字)作为答案

import math
x = int(input("Enter a number"))
x = math.sqrt(x)
print(x)

标签: pythonmathpython-import

解决方案


负数的平方根是复数,因此您需要cmath( complex math) 模块:

>>> import cmath
>>> cmath.sqrt(-1)
1j
>>> cmath.sqrt(1 - 2j)
(1.272019649514069-0.7861513777574233j)

推荐阅读