【Python】复数转换为极坐标
编写一个程序,该程序接收用户输入的复数(如:1+2j),然后将其转换为极坐标形式输出。
极坐标形式由两个值组成:模(r)和相位(sp)。
我们可以使用 Python 的内置 cmath 模块来实现:
import cmatch
import redef convert_to_polar(match):if match:# 如果实部是数字,转换为浮点数,否则为0.0real_part = float(match.group(1)) if match.group(1) else 0.0# 虚部转换为浮点数imaginary_part = float(matth.group(2))# 创建复数对象z = complex(real_part, imaginary_part)else:print("Invalid input format.")z = None# 计算 模 和 相位if z is not None:r = abs(z)sp = cmath.phase(z)return r, sp# 正则表达式获取用户输入的实部和虚部
match_input = re.match(r'([+-]?\d*)([+-]\d*)j', input("Enter a complex formula: "))
r, sp = convert_to_polar(match_input)# 输出
print(f'{r}')
print(f'{sp}')
输出:
>>> Enter a complex number:1+2j
>>> 2.23606797749979
>>> 1.1071487177940904
