Calculating Powers in Unity

I really enjoyed the Unity explanation, it’s nice to see how other APIs handle the same things. UE4 doesn’t seem to be that different from the way Unity does it.

Here is my code in UE4:

void UMathProblems::BeginPlay()
{
Super::BeginPlay();

float PowerBase = 2.0;
float PowerSuper = 24.0;

UE_LOG(LogTemp, Warning, TEXT("%f"), FMath::Pow(PowerBase, PowerSuper))

}

Output Log

LogTemp: Warning: 16777216.000000

1 Like

In python it’s like this:

print(pow(2, 24))

output: 16777216

You can try it out too. Just go to https://colab.research.google.com/, create a new notebook, and then type the code in.

1 Like
public void Start()
{ 
        int baseNum = 2;
        int exponent = 24;
        CalculatePower(baseNum, exponent);
}

public void CalculatePower(double numBase, double exponent)
{
        Debug.Log(numBase + " raised to the power of " + exponent + " is " + 
        System.Math.Pow(numBase, exponent));
}
1 Like

Since I’m on laptop still w/o visual studio I’m going to do this in python, then take a swing at C++ for UE4, but I can’t really test it.

print(2 ** 24)

result:

16777216

Process finished with exit code 0

for unreal I’d probably do

void UTestProgram::BeginPlay()
{
    Super::BeginPlay();
    int32 result  = FMath::Pow(2 , 24);

    UE_LOG(LogTemp, Warning, TEXT("2 ^ 24 = %i"), result);
}

Here’s using a web C++ compiler though:

#include <iostream>
#include <math.h>

using namespace std;

int main()
{

    int a = pow(2, 24);
   cout << ("2 ^ 24 = %i", a) << endl; 
   
   return 0;
}

result:

$g++ -o main *.cpp
$main
16777216
1 Like

python

print( pow( 2, 24 ))

thanks everyone for the wide range of examples and discussion!

1 Like

2 to the power of 24 in python
import math

number = int(input(" Please Enter any Positive Integer : “))
exponent = int(input(” Please Enter Exponent Value : "))

power = math.pow(number, exponent)

print(“The Result of {0} Power {1} = {2}”.format(number, exponent, power))

1 Like

This is how i did it in Unity:

Debug.Log(Mathf.Pow(2,24).ToString("#0"));

1 Like

I did it the Unity Bolt Visual Scripting way :smiley:

1 Like

Not quite sure what value type to use so I just used int

1 Like

If you’re only using whole numbers you can store the result in an int, so that’s absolutely fine in this case.
However, if you’re number or exponent include decimals then you should use a float or double, depending on the level of precision required (a float is fine 99.9% of the time) .

1 Like

Here’s Unity’s way of doing it:

    void Start()
    {
        float number = 2f;
        float exponent = 24f;
        float result = Mathf.Pow(number, exponent);

        Debug.Log("result: " + result);
    }

Prints result: 1.677722E+07
Must be a pretty big number…

Great work @David2.
The number isn’t too big. Remember that the E+07 is just telling you to move the decimal place 7 spaces to the right - So the full number would be 16,777,220.

This is how I did it. Good to know about the System.Math.Pow for using doubles if I need the precision.

I ended up using .NetFiddle for working on code this time around, so here was the code:

using System;

public class Program
{
	public static void Main()
	{
		double baseValue = 2;
		double exponentValue = 24;
		double result = Math.Pow(baseValue, exponentValue);
		Console.WriteLine("2^24 = " + result);
	}
}

And here was the output:

2^24 = 16777216

UE4.27 C++

void AMathTester::BeginPlay()
{
	Super::BeginPlay();

	if (GEngine)
	{
		float mathAnswer = FMath::Pow(2, 24);
		GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Green, FString::Printf(TEXT("%f"), mathAnswer));
	}
}

1 Like

Here’s my attempt - using Visual Studio and Unity:


I’ll definitely be taking advantage of using System.Math.Pow vs. Mathf.Pow from now on though, as I’m not much one for scientific notation if I don’t need it ha! That was a great bit of clarity that I’m sure I would’ve been scouring to find at some later date.

1 Like

Here’s my attemp. I was curious how fast is Math.Pow vs simple for loop based multiplication, so I did few benchmarks using BenchmarkDotNet.

Ryzen 2600x, Windows 10.0.19043 Build 19043, 16GB Ram ~3000MHz, and .NET6

Main.cs

using BenchmarkDotNet.Running;
using math_part_2;

//question
//Console.WriteLine(Math.Pow(2, 24));

//some tests
//var benchmarks = new SquaringBenchmarks();

//Console.WriteLine(benchmarks.MathPow());
//Console.WriteLine(benchmarks.ForPow());

//benchmarks!
BenchmarkRunner.Run<SquaringBenchmarks>();

Benchmarked code

	public class SquaringBenchmarks
	{
		[Benchmark]
		public double ForPow()
		{
			var number = 2;

			for (int i = 1; i < 24; i++)
			{
				number *= 2;
			}

			return number;
		}

		[Benchmark]
		public double MathPow()
		{
			return Math.Pow(2, 24);
		}
	}

Results, I’m surprised…

|  Method |      Mean |     Error |    StdDev |
|-------- |----------:|----------:|----------:|
|  ForPow |  9.286 ns | 0.0783 ns | 0.0694 ns |
| MathPow | 24.947 ns | 0.2402 ns | 0.2129 ns |
2 Likes

It’s interesting that your own was so much faster. (Although both are fast)

1 Like

Just for fun, here’s one with Linq using integer parameters, and an expression body.

private int Pow(int a, int b)
    => Enumerable.Repeat(a, b).Aggregate(1, (x, y) => x *= y);

PS: @garypettie
Your hand-rolled Pow is faulty because it takes in double's, but processes it as if they are integers.

Pow(2, 2.5) returns 8 when it should return 5.65685424949238

1 Like

Privacy & Terms