给定2 ^ n,使用对数找到n [英] Given 2^n, find n using logarithm

查看:80
本文介绍了给定2 ^ n,使用对数找到n的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个整数(2 ^ n),它是2的幂,我想使用对数找到n,即索引值.查找索引的公式是:log(number)/log(2).以下是代码段:

Given a integer(2^n) which is power of 2, I want to find out n, the index value using logarithm. The formula to find index is : log(number) / log(2). Following is the code snippet :

  unsigned long int a;
  double apower;
  apower = log((double)a) / log((double)2);

我发现'apower'的值在a的某个较大值上是错误的,我不知道该值,因为在我提交代码后,我的代码失败了.为什么会这样呢?是否存在一些强制转换问题?

I found that value of 'apower' is wrong at some large value of a, I do not know the value, as my code fails, after I submit it. Why is it so? Is there some casting issue?

下面是整个代码段:

  int count = 0;
  unsigned long int a,b;
  double apower,bpower;
  apower = log((double)a) / log((double)2);
  bpower = log((double)b) / log((double)2);
  count = abs(apower - bpower);
  printf("%d\n",count);

a和b的值始终为2的幂.因此apower和bpower的小数位必须为00.这就是为什么count的值将为int(%d). 我只想知道对数的行为.

Values of a and b will always be power of 2. So apower and bpower must be have 00 in decimal places. That is why, value of count will be int (%d). I just want to know the behavior of Logarithm.

推荐答案

使用double数学时,对数结果或商可能不完全是数学结果,而是1(或2)个下一个可表示的double.

When using double math, the log result or quotient may not be exactly the mathematical result but 1 (or 2) next representable double away.

计算log()仅返回log(0)的精确数学结果,所有其他数学结果都是非理性的.所有double都是理性的.

Calculating log() only returns an exact mathematical result for log(0), all other mathematical results are irrational. All double are rational.

这可能会导致出现诸如29.999999 ...之类的答案,该答案另存为int为29.

This may result in an answer like 29.999999..., which saved as an int is 29.

建议改用整数数学

int mylog2(unsigned long x) {
  int y = 0;
  #if (ULONG_MAX>>16 > 1lu<<16)
    if (x >= 1lu<<32) { x >>= 32; y += 32;
  #endif
  if (x >= 1lu<<16) { x >>= 16; y += 16; }
  if (x >= 1lu<<8) { x >>= 8; y += 8; }
  if (x >= 1lu<<4) { x >>= 4; y += 4; }
  if (x >= 1lu<<2) { x >>= 2; y += 2; }
  if (x >= 1lu<<1) { x >>= 1; y += 1; }
  return y;
}

这篇关于给定2 ^ n,使用对数找到n的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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