2^x = ?
BlitzMax Forums/BlitzMax Programming/2^x = ?
| ||
I clearly don't understand how Power works as this codeLocal check_flag:Int = 0 For Local conflict_id:Int = 0 Until 8 check_flag = 2^conflict_id DebugLog "2^" +conflict_id + " = " +check_flag Next Produces this output: DebugLog:2^0 = 1 DebugLog:2^1 = 2 DebugLog:2^2 = 4 DebugLog:2^3 = 7 DebugLog:2^4 = 15 DebugLog:2^5 = 32 DebugLog:2^6 = 63 DebugLog:2^7 = 127 Why aren't the numbers (bar 1) all even? |
| ||
This happens because of very small inaccuracies in the exponentiation function ( corresponding to the MinGW pow( ) function ) and the fact that floating point values are coverted to integer by chopping off anything after the decimal point. Thus a number like 7.9999999... becomes 7 rather than 8. The problem will be fixed with the next BlitzMax update, which uses a recent version of MinGW and an improved pow(). |
| ||
Thanks Floyd. That makes sense - nice to know it's being fixed! |
| ||
BlitzMAX doesn't use MinGW's pow() function at all. Mark opted to write a faster, but less accurate version which is called bbFloatPow(). The newer version of MinGW does handle floating point math more accurately, which in turn will allow bbFloatPow() to return more accurate results. But if you are not wanting to wait for the next BMAX version with newer MinGW, or not wanting to fudge about trying to get the newer MinGW to work with the current BMAX, then you can call MinGW's pow() function directly. Extern Function pow:Double(x:Double,y:Double) End Extern Local check_flag:Int = 0 For Local conflict_id:Int = 0 Until 8 check_flag = pow(2,conflict_id) DebugLog "2^" +conflict_id + " = " +check_flag Next |
| ||
Local check_flag:Int = 0 For Local conflict_id:Int = 0 Until 8 check_flag = Ceil (2^conflict_id) DebugLog "2^" +conflict_id + " = " +check_flag Next |
| ||
Thanks for those great (and instructive!) alternatives, but I think I'll just play it safe and check against this array:Global CheckFlag:Int[] = [.. %0000000000000001,.. %0000000000000010,.. %0000000000000100,.. %0000000000001000,.. %0000000000010000,.. %0000000000100000,.. %0000000001000000,.. %0000000010000000,.. %0000000100000000,.. %0000001000000000,.. %0000010000000000,.. %0000100000000000,.. %0001000000000000,.. %0010000000000000,.. %0100000000000000,.. %1000000000000000.. ] Actually... scratch that. I'll do this instead :) Local check_flag:Int = 1 For Local conflict_id:Int = 0 Until 8 DebugLog "2^" +conflict_id + " = " +check_flag check_flag :Shl 1 Next David |
| ||
congrats. First one that realized that 2^x is crap anyway and that shl and shr aren't there just for fun :-) |
| ||
With the latest MinGW, Blitzmax 1.24 returns the following results: 2^0 = 1 2^1 = 2 2^2 = 4 2^3 = 8 2^4 = 16 2^5 = 32 2^6 = 64 2^7 = 128 |