首页 > 解决方案 > 我在 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)  

标签: python

解决方案


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

推荐阅读