246

For example, does an operator exist to handle this?

float Result, Number1, Number2;

Number1 = 2;
Number2 = 2;

Result = Number1 (operator) Number2;

In the past the ^ operator has served as an exponential operator in other languages, but in C# it is a bit-wise operator.

Do I have to write a loop or include another namespace to handle exponential operations? If so, how do I handle exponential operations using non-integers?

4
  • 9
    It's not in C#, but many languages use ** as the infix exponentiation operator. Jun 14, 2010 at 1:41
  • 2
    came here because I was miffed that 10 ^ 7 stored in a long/Int64 was giving me "13." I had tried 1E7 also, but that gave me a type error. As I wasn't seeing a type error/illegal operator syntax error, I had assumed my 10^7 was working...
    – mpag
    Oct 19, 2017 at 19:47
  • 2
    @mpag ^ is the exclusive or operator, so 10^7 = 1010b XOR 0111b = 1101b = 13. May 13, 2020 at 15:06
  • 3
    C, C++, and C# have no exponentiation operator. They use the symbol ^ for bitwise exclusive-or, so it seems unwise to overload ^ as exponentiation (despite BASIC's long tradition). If someone wants to add an exponentiation operator, other choices have merit too. • FORTRAN's ** is sensible because exponentiation is "the level after" multiplication (*). • Knuth's is sensible because exponentiation is "the level before" tetration (↑↑). (Every possibility has pros and cons (and history).) See en.wikipedia.org/wiki/Exponentiation#In_programming_languages
    – A876
    Apr 26, 2021 at 21:47

9 Answers 9

291

The C# language doesn't have a power operator. However, the .NET Framework offers the Math.Pow method:

Returns a specified number raised to the specified power.

So your example would look like this:

float Result, Number1, Number2;

Number1 = 2;
Number2 = 2;

Result = Math.Pow(Number1, Number2);
6
  • 1
    Keep in mind the performance penalty if using Math.Pow for squaring: stackoverflow.com/questions/936541/…
    – Justas
    Aug 28, 2017 at 21:11
  • 8
    @Justas I just testing that on .NET Core 2.1 and Math.Pow is now faster than the suggested alternative implementation.
    – bytedev
    Dec 19, 2018 at 11:19
  • 1
    learned this the hardway when trying to debug why my calculation didn't work with a ^ Sep 26, 2020 at 15:19
  • 1
    But you still cannot use it to define constants as they have to be defined at compile-time and Math.Pow() is used at runtime.
    – z33k
    Nov 6, 2020 at 11:36
  • 1
    As @z33k said, no constants which also means no Enums. This is sad since it makes Flags Enums way more easy to read.
    – bkqc
    Feb 12, 2021 at 22:51
65

I stumbled on this post looking to use scientific notation in my code, I used

4.95*Math.Pow(10,-10);

But afterwards I found out you can do

4.95E-10;

Just thought I would add this for anyone in a similar situation that I was in.

1
  • 3
    Just keep in my mind that E is always a base-10 exponential. I know if we look closely, we understand this but since the OP was about general exponent, I thought it deserved to be highlighted.
    – bkqc
    Feb 12, 2021 at 22:22
35

There is a blog post on MSDN about why an exponent operator does NOT exists from the C# team.

It would be possible to add a power operator to the language, but performing this operation is a fairly rare thing to do in most programs, and it doesn't seem justified to add an operator when calling Math.Pow() is simple.


You asked:

Do I have to write a loop or include another namespace to handle exponential operations? If so, how do I handle exponential operations using non-integers?

Math.Pow supports double parameters so there is no need for you to write your own.

4
  • 32
    I understand the argument, but a valid reason would be that Math.Pow() cannot be used to set const values, which makes exponents unusable for all constants.
    – jsmars
    Mar 19, 2014 at 8:44
  • 1
    A power operator would be convenient for operator overloading, to me Math.Pow() does not justify that fact of not creating an exponent operator as Math.Pow() is not an operator an thus has not the same usages as an operator ._. Dec 30, 2018 at 13:35
  • 2
    It is a fairly common thing to want to do when writing Unity games in C# and the time spent doing double precision exponentiation is wasted when all you want is integral powers of integers like 2^X or X^2 or X^3 or something like that. I need it all the time.
    – lamont
    Jul 5, 2021 at 0:32
  • I don't mind that much when it takes a bit longer, but Math.Pow uses Doubles which are not precise. A simple addition of to integer values converted to doubles can give something like n-1.99999999999742 and then one truncates it back into an integer and gets n-1 instead of n.
    – Christoph
    Aug 4, 2021 at 23:13
14

The lack of an exponential operator for C# was a big annoyance for us when looking for a new language to convert our calculation software to from the good ol' vb6.

I'm glad we went with C# but it still annoys me whenever I'm writing a complex equation including exponents. The Math.Pow() method makes equations quite hard to read IMO.

Our solution was to create a special DoubleX class where we override the ^-operator (see below)

This works fairly well as long as you declare at least one of the variables as DoubleX:

DoubleX a = 2;
DoubleX b = 3;

Console.WriteLine($"a = {a}, b = {b}, a^b = {a ^ b}");

or use an explicit converter on standard doubles:

double c = 2;
double d = 3;

Console.WriteLine($"c = {c}, d = {d}, c^d = {c ^ (DoubleX)d}");     // Need explicit converter

One problem with this method though is that the exponent is calculated in the wrong order compared to other operators. This can be avoided by always putting an extra ( ) around the operation which again makes it a bit harder to read the equations:

DoubleX a = 2;
DoubleX b = 3;

Console.WriteLine($"a = {a}, b = {b}, 3+a^b = {3 + a ^ b}");        // Wrong result
Console.WriteLine($"a = {a}, b = {b}, 3+a^b = {3 + (a ^ b)}");      // Correct result

I hope this can be of help to others who uses a lot of complex equations in their code, and maybe someone even has an idea of how to improve this method?!

DoubleX class:

using System;

namespace ExponentialOperator
{
    /// <summary>
    /// Double class that uses ^ as exponential operator
    /// </summary>
    public class DoubleX
    {
        #region ---------------- Fields ----------------

        private readonly double _value;

        #endregion ------------- Fields ----------------

        #region -------------- Properties --------------

        public double Value
        {
            get { return _value; }
        }

        #endregion ----------- Properties --------------

        #region ------------- Constructors -------------

        public DoubleX(double value)
        {
            _value = value;
        }

        public DoubleX(int value)
        {
            _value = Convert.ToDouble(value);
        }

        #endregion ---------- Constructors -------------

        #region --------------- Methods ----------------

        public override string ToString()
        {
            return _value.ToString();
        }

        #endregion ------------ Methods ----------------

        #region -------------- Operators ---------------

        // Change the ^ operator to be used for exponents.

        public static DoubleX operator ^(DoubleX value, DoubleX exponent)
        {
            return Math.Pow(value, exponent);
        }

        public static DoubleX operator ^(DoubleX value, double exponent)
        {
            return Math.Pow(value, exponent);
        }

        public static DoubleX operator ^(double value, DoubleX exponent)
        {
            return Math.Pow(value, exponent);
        }

        public static DoubleX operator ^(DoubleX value, int exponent)
        {
            return Math.Pow(value, exponent);
        }

        #endregion ----------- Operators ---------------

        #region -------------- Converters --------------

        // Allow implicit convertion

        public static implicit operator DoubleX(double value)
        {
            return new DoubleX(value);
        }

        public static implicit operator DoubleX(int value)
        {
            return new DoubleX(value);
        }

        public static implicit operator Double(DoubleX value)
        {
            return value._value;
        }

        #endregion ----------- Converters --------------
    }
}
5

Since no-one has yet wrote a function to do this with two integers, here's one way:

private static long CalculatePower(int number, int powerOf)
{
    long result = number;
    for (int i = 2; i <= powerOf; i++)
        result *= number;
    return result;
}

Alternatively in VB.NET:

Private Function CalculatePower(ByVal number As Integer, ByVal powerOf As Integer) As Long
    Dim result As Long = number
    For i As Integer = 2 To powerOf
        result = result * number
    Next
    Return result
End Function
CalculatePower(5, 3) ' 125
CalculatePower(8, 4) ' 4096
CalculatePower(6, 2) ' 36
6
  • Can someone please explain the downvote? I've tested this code and you can too at ideone.com/o9mmAo (C#) & ideone.com/vnaczj (VB.NET) - it appears to work perfectly well.
    – Nathangrad
    Sep 9, 2016 at 15:30
  • 16
    Because there are Math.Pow so your code is irrelevance
    – Thaina Yu
    Oct 25, 2016 at 4:36
  • 1
    Math.Pow() is slow though and this will be substantially faster as long as PowerOf is reasonably small.
    – lamont
    Aug 26, 2017 at 22:18
  • 6
    @Nathangrad Reinventing the (square) wheel is largely considered an anti-pattern. FYI: exceptionnotfound.net/…
    – bytedev
    Dec 19, 2018 at 11:22
  • 2
    is the VB .NET version really required?? since VB .NET already has the exponent operator... Apr 28, 2021 at 5:24
3

For what it's worth I do miss the ^ operator when raising a power of 2 to define a binary constant. Can't use Math.Pow() there, but shifting an unsigned int of 1 to the left by the exponent's value works. When I needed to define a constant of (2^24)-1:

public static int Phase_count = 24;
public static uint PatternDecimal_Max = ((uint)1 << Phase_count) - 1;

Remember the types must be (uint) << (int).

1
  • For small numbers (like Flags Enums) you can simply use 0 -> 0 | 1 -> 1 << 0 | 2 -> 1 <<1 | 4 -> 1 <<2| ...
    – bkqc
    Feb 12, 2021 at 23:01
2

I'm surprised no one has mentioned this, but for the simple (and probably most encountered) case of squaring, you just multiply by itself.

float someNumber;

float result = someNumber * someNumber;
3
  • 4
    its not multiplication, its power of.
    – Henry
    Feb 9, 2017 at 19:13
  • Yes @Henry and as others have mentioned, an operator doesn't exist. Just Math.Pow. I was just offering up an obvious solution to the most common case.
    – RubberDuck
    Feb 9, 2017 at 19:24
  • 5
    Also much faster than Math.Pow(Number1, 2)
    – lamont
    Aug 26, 2017 at 22:18
0

A good power function would be

public long Power(int number, int power) {
    if (number == 0) return 0;
    long t = number;
    int e = power;
    int result = 1;
    for(i=0; i<sizeof(int); i++) {
        if (e & 1 == 1) result *= t;
        e >>= 1;
        if (e==0) break;
        t = t * t;
    }
}

The Math.Pow function uses the processor power function and is more efficient.

0

It's no operator but you can write your own extension function.

public static double Pow(this double value, double exponent)
{
    return Math.Pow(value, exponent);
}

This allows you to write

a.Pow(b);

instead of

Math.Pow(a, b);

I think that makes the relation between a and b a bit clearer + you avoid writing 'Math' over and over again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.