For this challenge, I thought it would be fun to share a few different ways of calculating 2^24 in Unity and the reasons why you might choose each option.
So, here are 4 potential options - Some good, others not so much. :
//1. The wrong way
Debug.Log(2^24);
//2. The long way
Debug.Log(2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2);
//3. The usual way
Debug.Log(UnityEngine.Mathf.Pow(2, 24));
//4. The precise way
Debug.Log(System.Math.Pow(2, 24));
And these produce the following resultsâŚ
So whatâs going on?
-
The wrong way:
Itâs quite common to use the caret (^) when writing super-script in plain text but in C# (and other languages) the caret is used as a binary XOR operator. In this example it basically looks at the binary representation of the two numbers and tells you where they differ, so so 00010 ^ 11000 = 11010, or 26. So this is definitely not the way to go. -
The long way:
This seems like a pretty ridiculous way of doing it but can have itâs advantages under certain conditions.
For 2^24 the readability and speed will both suffer, but for smaller exponents it can sometimes be a better option to just multiply them out and avoid the POW functions. -
The usual way:
Ok, this how we usually do it but whatâs with the weird answer. In this case the answer is being converted into scientific notation. Luckily for us there is no loss of precision in this example (even though it looks like there might be), so we could cast this back to an integer and be just fine. -
The precise way:
SinceUnityEngine.Mathf.Pow
only accepts floats, we can run into precision problems with larger numbers. When that happens we can always fall back on the trusty System.Math.Pow, which accepts doubles. Since doubles are twice as large as floats, it can give us more precision at the expense of using more memory. -
The DIY way:
Wait, I said 4 examples. Yeah⌠well⌠you read this far so hereâs a bonus!
You could also write your own Pow function if you were bored enough.
There are a few ways of doing it but hereâs one example. Just note that itâs almost always better to use the built in functions since theyâve usually been tested and optimised far better than something you write yourself (at least in my case!)
double Pow (double a, double b) {
double result = 1;
for (int i = 0; i < b; i++) {
result *= a;
}
return result;
}
So there you have it. Iâm almost certainly missing some other methods, but hopefully this covers the majority of them. Thanks for reading!