python - 我在 c++ 中有一个 do while 循环,但我试图将其转换为 python 代码
问题描述
我正在尝试找到根,所以我尝试将这个 c++ 函数转换为 python,但它不会工作
float computeRoot(float root,int index) {
float tp,mid,low=0.0,high=root;
do {
mid=(low+high)/2;
if(computePower(mid,index)>root)
high=mid;
else
low=mid;
mid=(low+high)/2;
tp=(computePower(mid,index)-root);
if (tp < 0) {
//grab absolute value
tp=-tp;
}
}while(tp>.000005); //accuracy of our root
return mid;
}
这是python代码
def computeRoot(a,b):
tp, mid,low = 0.0
while tp > 0.000005:
high = a
mid = (low +high) / 2
if Power(mid, b)> a:
high = mid
else:
low = mid
mid = (low + high)/2
tp = (Power(mid, b)- a)
if tp <0:
tp =-tp
print(mid)
解决方案
在do-while
检查条件之前保证循环一次。Python 中相应的习惯用法是在主体末尾使用带有显式条件检查的无限循环。如果条件为真,则中断。(请注意,与原始 C 中的条件相比,该条件被否定。)
def computeRoot(root, index):
low = 0.0
high = root
while True:
mid = (low + high) / 2
if computePower(mid, index) > root:
high = mid
else:
low = mid
mid = (low + high) / 2
tp = computePower(mid, index) - root
if tp < 0:
tp = -tp
if tp <= 0.000005:
break
return mid
简而言之,
do {
...
} while (<condition>)
变成
while True:
...
if not <condition>:
break
推荐阅读
- javascript - 仅在方法返回承诺完成后调用 then
- python - 我有一个无向 NetworkX 图,想找到 node_a 的所有邻居,它们也是 node_b 的邻居
- python - 装饰器函数使用 *args 和 **kargs 作为其 __call__ 方法的参数,
- oracle - 有没有办法动态调整 oracle UCP 最大大小?
- opencart - 在产品页面和搜索页面的价格下显示重量
- java - 创建自定义注释时,AnnotationProcessor vs ConstraintValidator 有什么用
- python - 如何在rest api中返回父产品,RecursiveField?
- python - 为什么我不能在 Django rest-framework unittest 中传递位置参数
- python - 使用python在postgresql数据库中插入json数据问题
- python - 使用范围函数显示消息