I need to use an unsigned double but it turns out C# does not provide such a type.
Does anyone know why?
As pointed out by Anders Forsgren, there is no unsigned doubles in the IEEE spec (and therefore not in C#).
You can always get the positive value by calling Math.Abs() and you could wrap a double in a struct and enforce the constraint there:
public struct PositiveDouble
{
private double _value;
public PositiveDouble() {}
public PositiveDouble(double val)
{
// or truncate/take Abs value automatically?
if (val < 0)
throw new ArgumentException("Value needs to be positive");
_value = val;
}
// This conversion is safe, we can make it implicit
public static implicit operator double(PositiveDouble d)
{
return d._value;
}
// This conversion is not always safe, so we make it explicit
public static explicit operator PositiveDouble(double d)
{
// or truncate/take Abs value automatically?
if (d < 0)
throw new ArgumentOutOfRangeException("Only positive values allowed");
return new PositiveDouble(d);
}
// add more cast operators if needed
}
Floating point numbers are simply the implementation of the IEEE 754 spec. There is no such thing as an unsigned double there as far as i know.
http://en.wikipedia.org/wiki/IEEE_754-2008
Why do you need an unsigned floating point number?
There is no such thing as an unsigned double in any language or system that I have ever heard of.
I need to give the ability to pass a variable that can be a fraction and must be positive. I wanted to use it in my Function signature to enforce it.
If you want to enforce a constraint that the parameter is positive, then you need to do that with a runtime check.
I rolled out a more detailed implementation of #Isak Savo's with tweaks here and there. Not sure if its perfect, but it's a great place to start.
public struct UDouble
{
/// <summary>
/// Equivalent to <see cref="double.Epsilon"/>.
/// </summary>
public static UDouble Epsilon = double.Epsilon;
/// <summary>
/// Represents the smallest possible value of <see cref="UDouble"/> (0).
/// </summary>
public static UDouble MinValue = 0d;
/// <summary>
/// Represents the largest possible value of <see cref="UDouble"/> (equivalent to <see cref="double.MaxValue"/>).
/// </summary>
public static UDouble MaxValue = double.MaxValue;
/// <summary>
/// Equivalent to <see cref="double.NaN"/>.
/// </summary>
public static UDouble NaN = double.NaN;
/// <summary>
/// Equivalent to <see cref="double.PositiveInfinity"/>.
/// </summary>
public static UDouble PositiveInfinity = double.PositiveInfinity;
double value;
public UDouble(double Value)
{
if (double.IsNegativeInfinity(Value))
throw new NotSupportedException();
value = Value < 0 ? 0 : Value;
}
public static implicit operator double(UDouble d)
{
return d.value;
}
public static implicit operator UDouble(double d)
{
return new UDouble(d);
}
public static bool operator <(UDouble a, UDouble b)
{
return a.value < b.value;
}
public static bool operator >(UDouble a, UDouble b)
{
return a.value > b.value;
}
public static bool operator ==(UDouble a, UDouble b)
{
return a.value == b.value;
}
public static bool operator !=(UDouble a, UDouble b)
{
return a.value != b.value;
}
public static bool operator <=(UDouble a, UDouble b)
{
return a.value <= b.value;
}
public static bool operator >=(UDouble a, UDouble b)
{
return a.value >= b.value;
}
public override bool Equals(object a)
{
return !(a is UDouble) ? false : this == (UDouble)a;
}
public override int GetHashCode()
{
return value.GetHashCode();
}
public override string ToString()
{
return value.ToString();
}
}
As to why one would need an unsigned double, consider that width and height dimensions of UI elements cannot be negative in most applications as that would be illogical; why, then, support negative numbers where they're not needed?
Some values like PositiveInfinity and NaN may still be applicable; therefore, we provide intuitive references to them. The big difference between double and UDouble is UDouble wouldn't need the constant NegativeInfinity (or at least I assume this much; I am not a mathematician, after all) and MinValue constant is simply 0. Also, Epsilon is positive, though, I am uncertain whether or not it is logical to use in the same context as unsigned numbers.
Note, this implementation automatically truncates negative numbers and an exception is thrown if you attempt to set to NegativeInfinity.
Related
I had a brilliant thought, that does not seem to be so brilliant afterwards, but maybe I don't understand the whole thing correctly.
I have a class, that stores some numbers. Some other functions/methods need int's and some need double's. So I thought I can create a class with a precision conversion implicitly.
public class PreciseInteger
{
public double PreciseValue {get; private set;}
public int RoundedValue {get; private set;}
public PreciseInteger(double value)
{
PreciseValue = value;
RoundedValue = (int)Math.Round(value, 0, MidpointRounding.AwayFromZero);
}
public static implicit operator PreciseInteger(int number)
{
return new PreciseInteger(number);
}
public static implicit operator PreciseInteger(double number)
{
return new PreciseInteger(number);
}
public static implicit operator int(PreciseInteger number)
{
return number.RoundedValue;
}
public static implicit operator double(PreciseInteger number)
{
return number.PreciseValue;
}
public override string ToString()
{
return PreciseValue.ToString();
}
}
And the class that uses this class is really a simple property storing class that does not much. So now I use somthing like
double myValue = myClass.StoredValue1 / myDivider;
But here I only get the integer value. I don't want to use an explicit casting (like Convert.ToDouble or (double)). So how could I make sure that the precise value is used and not the rounded one? Or did I misunderstand the whole concept and that doesn't work at all and I would have to use something like MyClass.MyDouble and MyClass.MyInteger values?
Edit: Ok, if I first say int newInt = myClass.StoredValue1 I get a rounded integer and if I use double newDouble = myClass.StoredValue1 I get the precise floating point number. But isn't there a way to say that one of them is always preferred?
The / operator is defined for both int and double:
double operator /(double x, double y);
int operator /(int x, int y);
These two overloads are both applicable when you do:
// assuming myClass.StoredValue1 and myDivider are PreciseIntegers
double myValue = myClass.StoredValue1 / myDivider;
because you defined an implicit conversion to int and an implicit conversion to double. However, the / that takes ints is actually a better function member, because int is a better conversion target, so the compiler always chooses the second overload.
One way to work around this is to define your own / operator for PreciseInteger:
public static PreciseInteger operator /(PreciseInteger number1, PreciseInteger number2) {
return number1.PreciseValue / number2.PreciseValue;
}
Then you can do:
double myValue = myClass.StoredValue1 / myDivider;
In C#, how it's possible to create custom type/cast for i.e. bool ? To better explain, i want that such expression:
bool cond=...;
int myVar= cond as customType;
so, i want customType to behave as myVar become either 0 or 1, depending of cond (if true, then 1, else 0).
Is that possible?
please, don't offer me cond ? 1 : 0 solution or others. I asked exactly what I asked, so re-read (or analyze) it if before flagging.
Yes, you can do so. If you want a custom type that behaves like a built-in type, you must take care to override some methods inherited from System.Object. Also, you need conversion operators.
Let's create a struct called Logical having an int property Value.
public readonly struct Logical : IEquatable<Logical>
{
public Logical(int value)
{
Value = value == 0 ? 0 : 1;
}
public Logical(bool cond)
{
Value = cond ? 1 : 0;
}
public int Value { get; }
... conversions and overrides
}
It has 2 constructors, allowing you to build a value from either an int or bool.
We can declare implicit conversions to convert between bool and Logical, int and Logical and Logical and bool.
public static implicit operator Logical(bool cond) => new Logical(cond);
public static implicit operator Logical(int i) => new Logical(i);
public static implicit operator bool(Logical logical) => logical.Value != 0;
It is also good to override Equals and GetHashCode to easily be able to compare values or to add them to dictionaries or hash sets.
public bool Equals(Logical other) // Implements IEquatable<Logical>
{
return Value.Equals(other.Value);
}
public override bool Equals(object obj)
{
if (obj is Logical logical) {
return Equals(logical);
}
return base.Equals(obj);
}
public override int GetHashCode() => Value.GetHashCode();
If you override Equals, it is natural to overload == and !=
public static bool operator ==(Logical a, Logical b) => a.Value == b.Value;
public static bool operator !=(Logical a, Logical b) => a.Value != b.Value;
Finally, we override ToString to be able to print Logicals.
public override string ToString() => Value == 0 ? "FALSE" : "TRUE";
Now, we can do these sort of things:
double x = 3.14;
Logical logical = x > 0.0;
bool b = logical;
Console.WriteLine($"logical = {logical}");
Console.WriteLine($"b = {b}");
logical = -3;
Console.WriteLine($"logical = {logical}");
Console.WriteLine($"logical.Value = {logical.Value}");
logical = 0;
Console.WriteLine($"logical = {logical}");
Console.ReadKey();
It prints:
logical = TRUE
b = True
logical = TRUE
logical.Value = 1
logical = FALSE
There is more you can do. System.Bool, for instance, implements IComparable, IComparable<bool>, IConvertible and IEquatable<bool>. It also has static Parse and TryParse methods. You could also overload other operators. See: Overloadable operators (Operator overloading, C# reference).
The answer here is probably the answer that you should be using unless you have a very good reason not to.
However, just because it's interesting, you could alternatively use some version of the following struct so that conversion is implicit and you have the bool value and the int value both available simultaneously without any extra memory usage:
[StructLayout(LayoutKind.Explicit)]
public struct BoolToInt
{
[FieldOffset(0)]
public readonly bool booleanValue;
[FieldOffset(0)]
public readonly int integerValue;
public BoolToInt(bool booleanValue)
{
this.integerValue = 0; //irrelevant, will be overwritten, but the compiler can't figure this out
this.booleanValue = booleanValue;
}
}
You could make the boolean value mutable if you want to be able to change it, however this does go against the general principles of struct usage.
I would strongly advise not making the integerValue field mutable.
If you need the value of a bool (1 or 0) you should use the GetHashCode function
Boolea.GetHashCode
I've put an example here
bool v1 = true;
bool v2 = false;
int res;
Console.WriteLine($"v1: {v1.GetHashCode()}, v2: {v2.GetHashCode()}");
I've noticed a difference between the behavior of user-defined implicit conversion to int and user-defined implicit conversion to an arbitrary struct MyStruct when applying operator==.
If I have:
public struct IntA
{
public IntA(int value)
{ m_value = value; }
public static implicit operator int(IntA a)
{ return a.m_value; }
private int m_value;
}
public struct IntB
{
public IntB(int value)
{ m_value = value; }
public static implicit operator int(IntB b)
{ return b.m_value; }
private int m_value;
}
Then the following code compiles:
{
var a = new IntA(3);
var b = new IntB(4);
bool equal = (a == b); // ok! converted to int and used int operator==
// ...
}
This uses my user-defined implicit operator int for IntA and IntB to convert to int, then invoke operator==(int, int).
However, if I have:
public struct MyStruct
{
public MyStruct(int value)
{ m_value = value; }
public static bool operator==(MyStruct lhs, MyStruct rhs)
{ return lhs.m_value == rhs.m_value; }
public static bool operator!=(MyStruct lhs, MyStruct rhs)
{ return lhs.m_value != rhs.m_value; }
private int m_value;
}
public struct MyStructA
{
public MyStructA(int value)
{ m_value = new MyStruct(value); }
public static implicit operator MyStruct(MyStructA a)
{ return a.m_value; }
private MyStruct m_value;
}
public struct MyStructB
{
public MyStructB(int value)
{ m_value = new MyStruct(value); }
public static implicit operator MyStruct(MyStructB b)
{ return b.m_value; }
private MyStruct m_value;
}
Then the following code does not compile:
{
var a = new MyStructA(3);
var b = new MyStructB(4);
bool equal = (a == b); // compile error: Operator `==' cannot be applied to operands of type `MyStructA' and `MyStructB'
// why can't it convert to MyStruct and use that operator==?
// ...
}
I expected it to do the same as the previous example, and use my user-defined implicit operator MyStruct to convert to MyStruct, then invoke operator==(MyStruct, MyStruct).
It doesn't do that. Why not? What's the different between these two cases from the compiler's perspective?
The answer is in the language spec. Emphasis is mine.
C# Language Specification 7.3.4
An operation of the form x op y, where op is an overloadable binary
operator, x is an expression of type X, and y is an expression of type
Y, is processed as follows:
The set of candidate user-defined operators provided by X and Y for the operation operator op(x, y) is determined. The set consists of
the union of the candidate operators provided by X and the candidate
operators provided by Y, each determined using the rules of §7.3.5.
If X and Y are the same type, or if X and Y are derived from a common
base type, then shared candidate operators only occur in the combined
set once.
If the set of candidate user-defined operators is not empty, then this becomes the set of candidate operators for the operation. Otherwise, the predefined binary operator op implementations, including their lifted forms, become the set of candidate operators
for the operation. The predefined implementations of a given
operator are specified in the description of the operator (§7.8
through §7.12). For predefined enum and delegate operators, the
only operators considered are those defined by an enum or delegate
type that is the binding-time type of one of the operands.
The overload resolution rules of §7.5.3 are applied to the set of candidate operators to select the best operator with respect to the
argument list (x, y), and this operator becomes the result of the
overload resolution process. If overload resolution fails to select a
single best operator, a binding-time error occurs.
So, if there's no initial match, it considers all the internally defined == operators as candidates. And since there is one for int, but not MyStruct, you see different behavior.
Why isn't there a bit structure in C#?
For what's worth, here is a full-fledged bit structure, complete with int and bool casting and arithmetic operations. Probably not perfect, but works fine for me. Enjoy!
/// <summary>
/// Represents a single bit that can be implicitly cast to/from and compared
/// with booleans and integers.
/// </summary>
/// <remarks>
/// <para>
/// An instance with a value of one is equal to any non-zero integer and is true,
/// an instance with a value of zero is equal to the integer zero and is false.
/// </para>
/// <para>
/// Arithmetic and logical AND, OR and NOT, as well as arithmetic XOR, are supported.
/// </para>
/// </remarks>
public struct Bit
{
/// <summary>
/// Creates a new instance with the specified value.
/// </summary>
/// <param name="value"></param>
public Bit(int value) : this()
{
Value = value == 0 ? 0 : 1;
}
/// <summary>
/// Gets the value of the bit, 0 or 1.
/// </summary>
public int Value { get; private set; }
#region Implicit conversions
public static implicit operator Bit(int value)
{
return new Bit(value);
}
public static implicit operator int(Bit value)
{
return value.Value;
}
public static implicit operator bool(Bit value)
{
return value.Value == 1;
}
public static implicit operator Bit(bool value)
{
return new Bit(value ? 1 : 0);
}
#endregion
#region Arithmetic operators
public static Bit operator |(Bit value1, Bit value2)
{
return value1.Value | value2.Value;
}
public static Bit operator &(Bit value1, Bit value2)
{
return value1.Value & value2.Value;
}
public static Bit operator ^(Bit value1, Bit value2)
{
return value1.Value ^ value2.Value;
}
public static Bit operator ~(Bit value)
{
return new Bit(value.Value ^ 1);
}
public static Bit operator !(Bit value)
{
return ~value;
}
#endregion
#region The true and false operators
public static bool operator true(Bit value)
{
return value.Value == 1;
}
public static bool operator false(Bit value)
{
return value.Value == 0;
}
#endregion
#region Comparison operators
public static bool operator ==(Bit bitValue, int intValue)
{
return
(bitValue.Value == 0 && intValue == 0) ||
(bitValue.Value == 1 && intValue != 0);
}
public static bool operator !=(Bit bitValue, int intValue)
{
return !(bitValue == intValue);
}
public override bool Equals(object obj)
{
if(obj is int)
return this == (int)obj;
else
return base.Equals(obj);
}
#endregion
}
It is called a boolean. At least, it would serve the basic function, right? You don't twiddle bits that often in C# (at least, I don't), and if you need to you can use the built in operations.
There is a BitArray class..
What would you want to do with it? Bear in mind that the CLR isn't going to try to pack multiple variables into a byte, so having one on its own would be no more useful than boolean. If you wanted to have a collection of them - well, that's what BitArray is for, as David pointed out.
If we did have a Bit structure, I suspect people would expect multiple Bit variables to be packed efficiently in memory - by not having the type in the first place, we avoid that expectation and lead people towards other solutions such as BitArray.
If you have a collection of bit flags, then using enums (with falgs attribute) and integers work a long way.
Though maybe there are rare exceptions, computers are not designed or intended to manipulate or allocate individual bits. Even at the lowest levels (assembly or pure machine language), you will not be able to allocate or access an individual bit. You have the same tools available in this regard as you have from any programming level: bytes and bitwise operations.
Along with the BitArray class already mentioned there is a also the more efficient BitVector32 Structure.
BitVector32 is more efficient than BitArray for Boolean values and
small integers that are used internally. A BitArray can grow
indefinitely as needed, but it has the memory and performance overhead
that a class instance requires. In contrast, a BitVector32 uses only
32 bits.
Keep in mind you are limited to 32 values.
Examples of BitVector32 usage at Dotnetpearls.com
You can do this now in C# 7.0!
public const int One = 0b0001;
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#numeric-literal-syntax-improvements
Is there any feasible way of using generics to create a Math library that does not depend on the base type chosen to store data?
In other words, let's assume I want to write a Fraction class. The fraction can be represented by two ints or two doubles or whatnot. The important thing is that the basic four arithmetic operations are well defined. So, I would like to be able to write Fraction<int> frac = new Fraction<int>(1,2) and/or Fraction<double> frac = new Fraction<double>(0.1, 1.0).
Unfortunately there is no interface representing the four basic operations (+,-,*,/). Has anybody found a workable, feasible way of implementing this?
Here is a way to abstract out the operators that is relatively painless.
abstract class MathProvider<T>
{
public abstract T Divide(T a, T b);
public abstract T Multiply(T a, T b);
public abstract T Add(T a, T b);
public abstract T Negate(T a);
public virtual T Subtract(T a, T b)
{
return Add(a, Negate(b));
}
}
class DoubleMathProvider : MathProvider<double>
{
public override double Divide(double a, double b)
{
return a / b;
}
public override double Multiply(double a, double b)
{
return a * b;
}
public override double Add(double a, double b)
{
return a + b;
}
public override double Negate(double a)
{
return -a;
}
}
class IntMathProvider : MathProvider<int>
{
public override int Divide(int a, int b)
{
return a / b;
}
public override int Multiply(int a, int b)
{
return a * b;
}
public override int Add(int a, int b)
{
return a + b;
}
public override int Negate(int a)
{
return -a;
}
}
class Fraction<T>
{
static MathProvider<T> _math;
// Notice this is a type constructor. It gets run the first time a
// variable of a specific type is declared for use.
// Having _math static reduces overhead.
static Fraction()
{
// This part of the code might be cleaner by once
// using reflection and finding all the implementors of
// MathProvider and assigning the instance by the one that
// matches T.
if (typeof(T) == typeof(double))
_math = new DoubleMathProvider() as MathProvider<T>;
else if (typeof(T) == typeof(int))
_math = new IntMathProvider() as MathProvider<T>;
// ... assign other options here.
if (_math == null)
throw new InvalidOperationException(
"Type " + typeof(T).ToString() + " is not supported by Fraction.");
}
// Immutable impementations are better.
public T Numerator { get; private set; }
public T Denominator { get; private set; }
public Fraction(T numerator, T denominator)
{
// We would want this to be reduced to simpilest terms.
// For that we would need GCD, abs, and remainder operations
// defined for each math provider.
Numerator = numerator;
Denominator = denominator;
}
public static Fraction<T> operator +(Fraction<T> a, Fraction<T> b)
{
return new Fraction<T>(
_math.Add(
_math.Multiply(a.Numerator, b.Denominator),
_math.Multiply(b.Numerator, a.Denominator)),
_math.Multiply(a.Denominator, b.Denominator));
}
public static Fraction<T> operator -(Fraction<T> a, Fraction<T> b)
{
return new Fraction<T>(
_math.Subtract(
_math.Multiply(a.Numerator, b.Denominator),
_math.Multiply(b.Numerator, a.Denominator)),
_math.Multiply(a.Denominator, b.Denominator));
}
public static Fraction<T> operator /(Fraction<T> a, Fraction<T> b)
{
return new Fraction<T>(
_math.Multiply(a.Numerator, b.Denominator),
_math.Multiply(a.Denominator, b.Numerator));
}
// ... other operators would follow.
}
If you fail to implement a type that you use, you will get a failure at runtime instead of at compile time (that is bad). The definition of the MathProvider<T> implementations is always going to be the same (also bad). I would suggest that you just avoid doing this in C# and use F# or some other language better suited to this level of abstraction.
Edit: Fixed definitions of add and subtract for Fraction<T>.
Another interesting and simple thing to do is implement a MathProvider that operates on an abstract syntax tree. This idea immediately points to doing things like automatic differentiation: http://conal.net/papers/beautiful-differentiation/
I believe this answers your question:
http://www.codeproject.com/KB/cs/genericnumerics.aspx
Here's a subtle problem that comes with generic types. Suppose an algorithm involves division, say Gaussian elimination to solve a system of equations. If you pass in integers, you'll get a wrong answer because you'll carry out integer division. But if you pass in double arguments that happen have integer values, you'll get the right answer.
The same thing happens with square roots, as in Cholesky factorization. Factoring an integer matrix will go wrong, whereas factoring a matrix of doubles that happen to have integer values will be fine.
First, your class should limit the generic parameter to primitives ( public class Fraction where T : struct, new() ).
Second, you'll probably need to create implicit cast overloads so you can handle casting from one type to another without the compiler crying.
Third, you can overload the four basic operators as well to make the interface more flexible when combining fractions of different types.
Lastly, you have to consider how you are handling arithmetic over and underflows. A good library is going to be extremely explicit in how it handles overflows; otherwise you cannot trust the outcome of operations of different fraction types.
The other approaches here will work, but they have a high performance impact over raw operators. I figured I would post this here for someone who needs the fastest, not the prettiest approach.
If you want to do generic math without paying a performance penalty, then this is, unfortunately, the way to do it:
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T IncrementToMax(T value)
{
if (typeof(T) == typeof(char))
return (char)(object)value! < char.MaxValue ? (T)(object)(char)((char)(object)value + 1) : value;
if (typeof(T) == typeof(byte))
return (byte)(object)value! < byte.MaxValue ? (T)(object)(byte)((byte)(object)value + 1) : value;
// ...rest of the types
}
It looks horrific, I know, but using this method will produce code that runs as fast as possible. The JIT will optimize out all the casts and conditional branches.
You can read the explanation and some additional important details here: http://www.singulink.com/codeindex/post/generic-math-at-raw-operator-speed
.NET 7 introduces a new feature - generic math (read more here and here) which is based on addition of static abstract interface methods. This feature introduces a lot of interfaces which allow to generically abstract over number types and/or math operations:
class Fraction<T> :
IAdditionOperators<Fraction<T>, Fraction<T>, Fraction<T>>,
ISubtractionOperators<Fraction<T>, Fraction<T>, Fraction<T>>,
IDivisionOperators<Fraction<T>, Fraction<T>, Fraction<T>>
where T : INumber<T>
{
public T Numerator { get; }
public T Denominator { get; }
public Fraction(T numerator, T denominator)
{
Numerator = numerator;
Denominator = denominator;
}
public static Fraction<T> operator +(Fraction<T> left, Fraction<T> right) =>
new(left.Numerator * right.Denominator + right.Numerator * left.Denominator,
left.Denominator * right.Denominator);
public static Fraction<T> operator -(Fraction<T> left, Fraction<T> right) =>
new(left.Numerator * right.Denominator - right.Numerator * left.Denominator,
left.Denominator * right.Denominator);
public static Fraction<T> operator /(Fraction<T> left, Fraction<T> right) =>
new(left.Numerator * right.Denominator, left.Denominator * right.Numerator);
}