python 负数开立方根
时间: 2023-09-08 09:15:47 浏览: 144
要计算Python中负数的立方根,可以使用以下代码片段:
```
cube = float(input('请输入一个数:'))
epsilon = 0.0001
low = -abs(cube)
high = abs(cube)
guess = (high + low) / 2.0
if cube == 0.0:
print(guess, '是', cube, '的立方根的近似解')
else:
while abs(guess**3 - abs(cube)) >= epsilon:
if guess**3 < abs(cube):
low = guess
else:
high = guess
guess = (high + low) / 2.0
if cube > 0:
print(guess, '是', cube, '的立方根的近似解')
else:
print('-', guess, '是', cube, '的立方根的近似解')
```
这段代码会先将`cube`的绝对值作为上界`high`,并将负的绝对值作为下界`low`,然后进行二分法计算立方根的近似解。如果输入的负数`cube`为0,则会直接输出`cube`作为立方根的近似解。最后,根据`cube`的正负性,分别输出结果。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [利用二分查找求实数立方根(python)](https://blog.csdn.net/zxy_0518/article/details/121505771)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文