A math question, I suppose
Blitz3D Forums/Blitz3D Programming/A math question, I suppose
| ||
I need to have a simple operation to convert a power value to an absolute value. For example 2^23 needs to be converted to 23. Any simple math operation that would permit this? Mod? I'm out of ideas... |
| ||
I don't follow. You want to parse a string "2^23" and retrieve "23"? Or you want to take the result of 2^23 and get a result of 23 again? |
| ||
Local a = Ceil(2^23) Local b = 1 While a>2 a = a/2 b = b+1 Wend Print b |
| ||
Generally, if a=b^c then c=log(a)/log(b) |
| ||
fredborg, indeed! Thanks!!! :D Yet, some problems arise, as this is for use with bit flags: Graphics 800, 600,32,2 For i = 0 To 31 a = Ceil(2^i) Local b = 1 While a>2 a = a/2 b = b+1 Wend Print "2^"+i+"="+b Next WaitKey() Nomen luni's idea: Graphics 800, 600,32,2 For i = 0 To 31 a=2^i c=Log(a)/Log(2) Print "2^"+i+"="+c Next WaitKey() Nomen luni's revision 2: Graphics 800, 600,32,2 For i = 0 To 31 a=2^i c=Log(a) * 1.4427 Print "2^"+i+"="+a+", which is bit "+c Next WaitKey() Now, this way I can get the bit value, and convert it back to the bit position, very nice. But I guess I'll have to forget using bit 31. |
| ||
Ah, well then this works:For i = 0 To 31 a = Ceil(2^i) Local b = -1 While a<>0 a = a Shr 1 b = b+1 Wend Print "2^"+i+"="+b Next |
| ||
Maybe I'm wrong, but Nomen's idea seems more a performance crown. :P |
| ||
Really ;( Without running I would have put my money on SHR reather than Log. Oh well |
| ||
H&K, but what is more performing: - A solution where you have an undetermined number of Shr in a looped Blitz3D code - A solution with a single Log() and multiplication ? But definately, fredborg's idea works for all bit values. Nomen's idea doesn't work for bit 31, from what I tried. Maybe I should just do a bit table LOL. I'm undecided! Here's the idea: Function Get_ON_bit(value%) Local bit% = -1 While value <> 0 And bit < 32 value = value Shr 1 bit = bit + 1 Wend Return bit End Function This is, considering the value only has one bit set, or is masked with one bit. |
| ||
The log method may not be as speedy as it appears as I imagine the log function is doing some internal loops to come up with an answer. |
| ||
On my system, "value a = b Shr c" takes 2ns, "value = Log(b)" takes 44ns. So, considering the odds of performing 30 Shr, vs the very solid 44ns of the Log(), I think fredborg's solution is the best for performance, and is giving 100% of the results I need. And with ferdborg's version, it's even faster than consulting a table in a loop. And if I want to convert absolute value to bit shifted value, that's as simple as "1 Shl 23"... Cheers. |
| ||
So without testing, my money was on the winner ;) |