log2()

Started by
6 comments, last by head_hunter 18 years, 4 months ago
The log2() function does not exist in visual studio's <math.h> or <cmath> libraries. How would I implement this using log10 or the natural log function?
Play my Crappy Games:Stantonia.com
Advertisement
Just to make sure, log2() is taking the log with base 2 of a number right? If such is the case, I just might be able to help. To take the log of a number with base x, simply use this handy dandy equation I learned back in Alg. 2 I think it was:

logx(n) = log(n)/log(x)

So in your case it would be:

log2(n) = log(n)/log(2)

Hope that helps you out.

-AJ
V/R,-AJThere are 10 kinds of people in the world: Those who understand binary and those who don't...
You need to use the Change of Base formula. It will require two log operations, so if speed is a concern, maybe a different way is better.

Log base a of x = log x / log a

so in your case,

log2(x) = log(x)/log(2)

good luck!

EDIT: Yeah, what he said ^
Thanks for the help my good fellows.
Play my Crappy Games:Stantonia.com
You don't by chance want an integer result do you? And you wouldn't happen to want to to be guaranteed that it's always rounded up would you? Also, perhaps you want a fast version of something with does exactly that?

If so, the following may interest you:
unsigned NextPow2(unsigned x) {    --x;    x |= x >> 1;    x |= x >> 2;    x |= x >> 4;    x |= x >> 8;    x |= x >> 16;    return ++x;}
This is blazingly fast compared to using floating-point log calls.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
To make another approximation known: If you want to yield the log2 with integer resolution from a float value, you could use something like this:
#include <stdint.h>inline static int32_t ldi(float arg) {	uint32_t exp = (((uint32_t&)arg)>>23)&0xff;	return int32_t(exp)-127;}


Here the exponent is isolated from a IEEE float, denormalized and returned.
Quote:Original post by haegarr
To make another approximation known: If you want to yield the log2 with integer resolution from a float value, you could use something like this:
#include <stdint.h>inline static int32_t ldi(float arg) {	uint32_t exp = (((uint32_t&)arg)>>23)&0xff;	return int32_t(exp)-127;} 

... or simply call frexp().
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!
You could also go this way:

	_asm	{		fld		qword ptr [factor]		fld		qword ptr [src]		fyl2x		fstp		qword ptr [dest]	}


where factor is a real number which will be multiplied to log2(src). The above code implements the assignment:

dest = factor * log2(src)

Notes:
1) if you don't want to multiply by a factor, you can replace the first instruction with fld1.
2) src, dest and factor are considered to be doubles. Replace qword with dword to work with floats.

This topic is closed to new replies.

Advertisement