Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do exponentiation in constant expression?

Having used the exponent operator ^ in the initialisation of a VB class's public constant following this question.

Public Const MaxValue As Double = MaxMantissa * (2 ^ MaxExponent)

I am converting the class to C#. however I find that C# does not have the same operator (^ is still an operator but only as bitwise xor).

Math.Pow() is given as an alternative to the operator, but cannot be used in a constant expression. How then can one initialise a constant with an exponent expression in C#?

(I do not use a value instead of an expression because the values within the expression, also constant, come from different places. MaxExponent comes from the base class, MaxMantissa is different in each derived class. Furthermore there are multiple constants like this in each derived class such as MaxPositiveValue, MinPositiveValue, MinNegativeValue, MaxNegativeValue, etc.)

like image 555
Toby Avatar asked May 31 '17 08:05

Toby


1 Answers

Since in your particular case you want to raise 2 into MaxExponent power

2 ** MaxExponent

you can put it as a left shift, but if and only if MaxExponent is a small positive integer value:

1 << MaxExponent

Like this

// double: see comments below `1L` stands for `long` and so MaxExponent = [0..63]   
public const double MaxValue = MaxMantissa * (1L << MaxExponent);

In general case (when MaxExponent is an arbitrary double value), you can try changing const to readonly

public static readonly double MaxValue = MaxMantissa * Math.Pow(2.0, MaxExponent);
like image 116
Dmitry Bychenko Avatar answered Sep 29 '22 10:09

Dmitry Bychenko