我在c ++中有一个do while循环,但我试图将其转换为python代码

时间:2019-02-21 15:07:01

标签: 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)  

3 个答案:

答案 0 :(得分:0)

您的代码在python中将如下所示:

def computeRoot(root,index):
    tp = 0
    mid = 0
    low = 0
    high = root
    while tp > 0.000005:
        mid = (low + high)/2
        if computePower(mid, index) > root:
            high = mid
        else:
            low = mid
        tp = computePower(mid,index) - root
        if (tp < 0):
            tp=-tp
    return mid

但是您想要这样的东西(数字的第n个根):

def computeRoot(root,index):
    if (index == 0):
        return 1
    else:
        return pow(root,(1/index))

答案 1 :(得分:0)

保证do-while循环在检查条件之前执行一次。 Python中相应的习惯用法是使用无限循环,并在主体的 end 处进行显式条件检查。如果条件为真,则中断。 (请注意,与原始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

答案 2 :(得分:0)

tp的初始值为零,因此您的函数将永远不会进入while循环,并且始终返回0

如果您希望在c ++答案之后在Python代码上添加while循环,则可以执行以下操作:

def computeRoot(root,b):
    tp , mid , low = 0 , 0 , 0
    while(tp>0.000005):
        high = root
        mid = (low+high) / 2
        if mid**b> root:
            high = mid
        else:
            low = mid
        mid = (low + high)/2
        tp = (mid**b)- root
        if tp <0:
            tp =-tp
    return mid

请注意,a ** b可以翻译Python中的power(a,b)函数