计算对数,这是为什么算法效率不高,以及如何使其更有效率? [英] Calculating logarithm, why is this algorithm not efficient, and how to make it more efficient?

查看:129
本文介绍了计算对数,这是为什么算法效率不高,以及如何使其更有效率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在想,如果我能计算出一批基于相对于基地数的对数(例如,日志16座2)实际上并没有使用日志()。我成功地做到这一点,但我不认为这是非常有效的。

I was wondering if I could calculate the logarithm of a number based on a number relative to a base (for example, log base 2 of 16) without actually using log(). I managed to do it, but I don't believe it is very efficient.

这是我的code在Python:

This is my code in Python:

def myLog(x,b):
    exp=0
    ans=b**exp
    while x!=ans:
        ans=b**exp
        if ans==x:
            return exp
        exp=exp+1

所以,我可以给它 myLog(16,2),它应该返回4.事实上确实如此,但我相信这不是最有效的方法,所以我怎么能解决这个问题,让我的code更有效,而不仅仅是在这种情况下,但在大多数人?

So I could give it myLog(16,2) and it should return 4. And indeed it does, however I believe it is not the most efficient way, so how could I fix it and make my code more efficient, not just in this case, but in most of them?

推荐答案

下面是我的两分钱的价值:

Here's my two cents worth:

def myLog(x,b):
    exp = 0
    ans = 1
    while ans<x:
        ans *= b
        exp += 1
    if ans == x:
        return exp  
    else:
        raise ValueError("can't find a suitable exponent")

In [10]: myLog(16,2)
Out[10]: 4

希望这有助于

Hope this helps

这篇关于计算对数,这是为什么算法效率不高,以及如何使其更有效率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆