// ========================================================== // FreeImage 3 .NET wrapper // Original FreeImage 3 functions and .NET compatible derived functions // // Design and implementation by // - Jean-Philippe Goerke (jpgoerke@users.sourceforge.net) // - Carsten Klein (cklein05@users.sourceforge.net) // // Contributors: // - David Boland (davidboland@vodafone.ie) // // Main reference : MSDN Knowlede Base // // This file is part of FreeImage 3 // // COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES // THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE // OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED // CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT // THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY // SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL // PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER // THIS DISCLAIMER. // // Use at your own risk! // ========================================================== // ========================================================== // CVS // $Revision: 1.5 $ // $Date: 2009/02/27 16:36:23 $ // $Id: FIRational.cs,v 1.5 2009/02/27 16:36:23 cklein05 Exp $ // ========================================================== using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Diagnostics; namespace FreeImageAPI { /// /// The FIRational structure represents a fraction via two /// instances which are interpreted as numerator and denominator. /// /// /// The structure tries to approximate the value of /// when creating a new instance by using a better algorithm than FreeImage does. /// /// The structure implements the following operators: /// +, -, ++, --, ==, != , >, >==, <, <== and ~ (which switches nominator and denomiator). /// /// The structure can be converted into all .NET standard types either implicit or /// explicit. /// [Serializable, StructLayout(LayoutKind.Sequential), ComVisible(true)] public struct FIRational : IConvertible, IComparable, IFormattable, IComparable, IEquatable { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private int numerator; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private int denominator; /// /// Represents the largest possible value of . This field is constant. /// public static readonly FIRational MaxValue = new FIRational(Int32.MaxValue, 1); /// /// Represents the smallest possible value of . This field is constant. /// public static readonly FIRational MinValue = new FIRational(Int32.MinValue, 1); /// /// Represents the smallest positive value greater than zero. This field is constant. /// public static readonly FIRational Epsilon = new FIRational(1, Int32.MaxValue); /// /// Initializes a new instance based on the specified parameters. /// /// The numerator. /// The denominator. public FIRational(int n, int d) { numerator = n; denominator = d; Normalize(); } /// /// Initializes a new instance based on the specified parameters. /// /// The tag to read the data from. public unsafe FIRational(FITAG tag) { switch (FreeImage.GetTagType(tag)) { case FREE_IMAGE_MDTYPE.FIDT_SRATIONAL: int* value = (int*)FreeImage.GetTagValue(tag); numerator = (int)value[0]; denominator = (int)value[1]; Normalize(); return; default: throw new ArgumentException("tag"); } } /// /// Initializes a new instance based on the specified parameters. /// /// The value to convert into a fraction. /// /// cannot be converted into a fraction /// represented by two integer values. public FIRational(decimal value) { try { int sign = value < 0 ? -1 : 1; value = Math.Abs(value); try { int[] contFract = CreateContinuedFraction(value); CreateFraction(contFract, out numerator, out denominator); Normalize(); } catch { numerator = 0; denominator = 1; } if (Math.Abs(((decimal)numerator / (decimal)denominator) - value) > 0.0001m) { int maxDen = (Int32.MaxValue / (int)value) - 2; maxDen = maxDen < 10000 ? maxDen : 10000; ApproximateFraction(value, maxDen, out numerator, out denominator); Normalize(); if (Math.Abs(((decimal)numerator / (decimal)denominator) - value) > 0.0001m) { throw new OverflowException("Unable to convert value into a fraction"); } } numerator *= sign; Normalize(); } catch (Exception ex) { throw new OverflowException("Unable to calculate fraction.", ex); } } /// /// The numerator of the fraction. /// public int Numerator { get { return numerator; } } /// /// The denominator of the fraction. /// public int Denominator { get { return denominator; } } /// /// Returns the truncated value of the fraction. /// /// public int Truncate() { return denominator > 0 ? (int)(numerator / denominator) : 0; } /// /// Returns whether the fraction is representing an integer value. /// public bool IsInteger { get { return (denominator == 1 || (denominator != 0 && (numerator % denominator == 0)) || (denominator == 0 && numerator == 0)); } } /// /// Calculated the greatest common divisor of 'a' and 'b'. /// private static long Gcd(long a, long b) { a = Math.Abs(a); b = Math.Abs(b); long r; while (b > 0) { r = a % b; a = b; b = r; } return a; } /// /// Calculated the smallest common multiple of 'a' and 'b'. /// private static long Scm(int n, int m) { return Math.Abs((long)n * (long)m) / Gcd(n, m); } /// /// Normalizes the fraction. /// private void Normalize() { if (denominator == 0) { numerator = 0; denominator = 1; return; } if (numerator != 1 && denominator != 1) { int common = (int)Gcd(numerator, denominator); if (common != 1 && common != 0) { numerator /= common; denominator /= common; } } if (denominator < 0) { numerator *= -1; denominator *= -1; } } /// /// Normalizes a fraction. /// private static void Normalize(ref long numerator, ref long denominator) { if (denominator == 0) { numerator = 0; denominator = 1; } else if (numerator != 1 && denominator != 1) { long common = Gcd(numerator, denominator); if (common != 1) { numerator /= common; denominator /= common; } } if (denominator < 0) { numerator *= -1; denominator *= -1; } } /// /// Returns the digits after the point. /// private static int GetDigits(decimal value) { int result = 0; value -= decimal.Truncate(value); while (value != 0) { value *= 10; value -= decimal.Truncate(value); result++; } return result; } /// /// Creates a continued fraction of a decimal value. /// private static int[] CreateContinuedFraction(decimal value) { int precision = GetDigits(value); decimal epsilon = 0.0000001m; List list = new List(); value = Math.Abs(value); byte b = 0; list.Add((int)value); value -= ((int)value); while (value != 0m) { if (++b == byte.MaxValue || value < epsilon) { break; } value = 1m / value; if (Math.Abs((Math.Round(value, precision - 1) - value)) < epsilon) { value = Math.Round(value, precision - 1); } list.Add((int)value); value -= ((int)value); } return list.ToArray(); } /// /// Creates a fraction from a continued fraction. /// private static void CreateFraction(int[] continuedFraction, out int numerator, out int denominator) { numerator = 1; denominator = 0; int temp; for (int i = continuedFraction.Length - 1; i > -1; i--) { temp = numerator; numerator = continuedFraction[i] * numerator + denominator; denominator = temp; } } /// /// Tries 'brute force' to approximate with a fraction. /// private static void ApproximateFraction(decimal value, int maxDen, out int num, out int den) { num = 0; den = 0; decimal bestDifference = 1m; decimal currentDifference = -1m; int digits = GetDigits(value); if (digits <= 9) { int mul = 1; for (int i = 1; i <= digits; i++) { mul *= 10; } if (mul <= maxDen) { num = (int)(value * mul); den = mul; return; } } for (int i = 1; i <= maxDen; i++) { int numerator = (int)Math.Floor(value * (decimal)i + 0.5m); currentDifference = Math.Abs(value - (decimal)numerator / (decimal)i); if (currentDifference < bestDifference) { num = numerator; den = i; bestDifference = currentDifference; } } } /// /// Converts the numeric value of the object /// to its equivalent string representation. /// /// The string representation of the value of this instance. public override string ToString() { return ((IConvertible)this).ToDouble(null).ToString(); } /// /// Tests whether the specified object is a structure /// and is equivalent to this structure. /// /// The object to test. /// true if is a structure /// equivalent to this structure; otherwise, false. public override bool Equals(object obj) { return ((obj is FIRational) && (this == ((FIRational)obj))); } /// /// Returns a hash code for this structure. /// /// An integer value that specifies the hash code for this . public override int GetHashCode() { return base.GetHashCode(); } #region Operators /// /// Standard implementation of the operator. /// public static FIRational operator +(FIRational r1) { return r1; } /// /// Standard implementation of the operator. /// public static FIRational operator -(FIRational r1) { r1.numerator *= -1; return r1; } /// /// Returns the reciprocal value of this instance. /// public static FIRational operator ~(FIRational r1) { int temp = r1.denominator; r1.denominator = r1.numerator; r1.numerator = temp; r1.Normalize(); return r1; } /// /// Standard implementation of the operator. /// public static FIRational operator ++(FIRational r1) { checked { r1.numerator += r1.denominator; } return r1; } /// /// Standard implementation of the operator. /// public static FIRational operator --(FIRational r1) { checked { r1.numerator -= r1.denominator; } return r1; } /// /// Standard implementation of the operator. /// public static FIRational operator +(FIRational r1, FIRational r2) { long numerator = 0; long denominator = Scm(r1.denominator, r2.denominator); numerator = (r1.numerator * (denominator / r1.denominator)) + (r2.numerator * (denominator / r2.denominator)); Normalize(ref numerator, ref denominator); checked { return new FIRational((int)numerator, (int)denominator); } } /// /// Standard implementation of the operator. /// public static FIRational operator -(FIRational r1, FIRational r2) { return r1 + (-r2); } /// /// Standard implementation of the operator. /// public static FIRational operator *(FIRational r1, FIRational r2) { long numerator = r1.numerator * r2.numerator; long denominator = r1.denominator * r2.denominator; Normalize(ref numerator, ref denominator); checked { return new FIRational((int)numerator, (int)denominator); } } /// /// Standard implementation of the operator. /// public static FIRational operator /(FIRational r1, FIRational r2) { int temp = r2.denominator; r2.denominator = r2.numerator; r2.numerator = temp; return r1 * r2; } /// /// Standard implementation of the operator. /// public static FIRational operator %(FIRational r1, FIRational r2) { r2.Normalize(); if (Math.Abs(r2.numerator) < r2.denominator) return new FIRational(0, 0); int div = (int)(r1 / r2); return r1 - (r2 * div); } /// /// Standard implementation of the operator. /// public static bool operator ==(FIRational r1, FIRational r2) { r1.Normalize(); r2.Normalize(); return (r1.numerator == r2.numerator) && (r1.denominator == r2.denominator); } /// /// Standard implementation of the operator. /// public static bool operator !=(FIRational r1, FIRational r2) { return !(r1 == r2); } /// /// Standard implementation of the operator. /// public static bool operator >(FIRational r1, FIRational r2) { long denominator = Scm(r1.denominator, r2.denominator); return (r1.numerator * (denominator / r1.denominator)) > (r2.numerator * (denominator / r2.denominator)); } /// /// Standard implementation of the operator. /// public static bool operator <(FIRational r1, FIRational r2) { long denominator = Scm(r1.denominator, r2.denominator); return (r1.numerator * (denominator / r1.denominator)) < (r2.numerator * (denominator / r2.denominator)); } /// /// Standard implementation of the operator. /// public static bool operator >=(FIRational r1, FIRational r2) { long denominator = Scm(r1.denominator, r2.denominator); return (r1.numerator * (denominator / r1.denominator)) >= (r2.numerator * (denominator / r2.denominator)); } /// /// Standard implementation of the operator. /// public static bool operator <=(FIRational r1, FIRational r2) { long denominator = Scm(r1.denominator, r2.denominator); return (r1.numerator * (denominator / r1.denominator)) <= (r2.numerator * (denominator / r2.denominator)); } #endregion #region Conversions /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator bool(FIRational value) { return (value.numerator != 0); } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator byte(FIRational value) { return (byte)(double)value; } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator char(FIRational value) { return (char)(double)value; } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static implicit operator decimal(FIRational value) { return value.denominator == 0 ? 0m : (decimal)value.numerator / (decimal)value.denominator; } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static implicit operator double(FIRational value) { return value.denominator == 0 ? 0d : (double)value.numerator / (double)value.denominator; } /// /// Converts the value of a structure to an structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator short(FIRational value) { return (short)(double)value; } /// /// Converts the value of a structure to an structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator int(FIRational value) { return (int)(double)value; } /// /// Converts the value of a structure to an structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator long(FIRational value) { return (byte)(double)value; } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static implicit operator float(FIRational value) { return value.denominator == 0 ? 0f : (float)value.numerator / (float)value.denominator; } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator sbyte(FIRational value) { return (sbyte)(double)value; } /// /// Converts the value of a structure to an structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator ushort(FIRational value) { return (ushort)(double)value; } /// /// Converts the value of a structure to an structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator uint(FIRational value) { return (uint)(double)value; } /// /// Converts the value of a structure to an structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator ulong(FIRational value) { return (ulong)(double)value; } // /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator FIRational(bool value) { return new FIRational(value ? 1 : 0, 1); } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static implicit operator FIRational(byte value) { return new FIRational(value, 1); } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static implicit operator FIRational(char value) { return new FIRational(value, 1); } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator FIRational(decimal value) { return new FIRational(value); } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator FIRational(double value) { return new FIRational((decimal)value); } /// /// Converts the value of an structure to a structure. /// /// An structure. /// A new instance of initialized to . public static implicit operator FIRational(short value) { return new FIRational(value, 1); } /// /// Converts the value of an structure to a structure. /// /// An structure. /// A new instance of initialized to . public static implicit operator FIRational(int value) { return new FIRational(value, 1); } /// /// Converts the value of an structure to a structure. /// /// An structure. /// A new instance of initialized to . public static explicit operator FIRational(long value) { return new FIRational((int)value, 1); } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static implicit operator FIRational(sbyte value) { return new FIRational(value, 1); } /// /// Converts the value of a structure to a structure. /// /// A structure. /// A new instance of initialized to . public static explicit operator FIRational(float value) { return new FIRational((decimal)value); } /// /// Converts the value of an structure to a structure. /// /// An structure. /// A new instance of initialized to . public static implicit operator FIRational(ushort value) { return new FIRational(value, 1); } /// /// Converts the value of an structure to a structure. /// /// An structure. /// A new instance of initialized to . public static explicit operator FIRational(uint value) { return new FIRational((int)value, 1); } /// /// Converts the value of an structure to a structure. /// /// An structure. /// A new instance of initialized to . public static explicit operator FIRational(ulong value) { return new FIRational((int)value, 1); } #endregion #region IConvertible Member TypeCode IConvertible.GetTypeCode() { return TypeCode.Double; } bool IConvertible.ToBoolean(IFormatProvider provider) { return (bool)this; } byte IConvertible.ToByte(IFormatProvider provider) { return (byte)this; } char IConvertible.ToChar(IFormatProvider provider) { return (char)this; } DateTime IConvertible.ToDateTime(IFormatProvider provider) { return Convert.ToDateTime(((IConvertible)this).ToDouble(provider)); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return this; } double IConvertible.ToDouble(IFormatProvider provider) { return this; } short IConvertible.ToInt16(IFormatProvider provider) { return (short)this; } int IConvertible.ToInt32(IFormatProvider provider) { return (int)this; } long IConvertible.ToInt64(IFormatProvider provider) { return (long)this; } sbyte IConvertible.ToSByte(IFormatProvider provider) { return (sbyte)this; } float IConvertible.ToSingle(IFormatProvider provider) { return this; } string IConvertible.ToString(IFormatProvider provider) { return ToString(((double)this).ToString(), provider); } object IConvertible.ToType(Type conversionType, IFormatProvider provider) { return Convert.ChangeType(((IConvertible)this).ToDouble(provider), conversionType, provider); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return (ushort)this; } uint IConvertible.ToUInt32(IFormatProvider provider) { return (uint)this; } ulong IConvertible.ToUInt64(IFormatProvider provider) { return (ulong)this; } #endregion #region IComparable Member /// /// Compares this instance with a specified . /// /// An object to compare with this instance. /// A 32-bit signed integer indicating the lexical relationship between the two comparands. /// is not a . public int CompareTo(object obj) { if (obj == null) { return 1; } if (!(obj is FIRational)) { throw new ArgumentException(); } return CompareTo((FIRational)obj); } #endregion #region IFormattable Member /// /// Formats the value of the current instance using the specified format. /// /// The String specifying the format to use. /// The IFormatProvider to use to format the value. /// A String containing the value of the current instance in the specified format. public string ToString(string format, IFormatProvider formatProvider) { if (format == null) { format = ""; } return String.Format(formatProvider, format, ((IConvertible)this).ToDouble(formatProvider)); } #endregion #region IEquatable Member /// /// Tests whether the specified structure is equivalent to this structure. /// /// A structure to compare to this instance. /// true if is a structure /// equivalent to this structure; otherwise, false. public bool Equals(FIRational other) { return (this == other); } #endregion #region IComparable Member /// /// Compares this instance with a specified object. /// /// A to compare. /// A signed number indicating the relative values of this instance /// and . public int CompareTo(FIRational other) { FIRational difference = this - other; difference.Normalize(); if (difference.numerator > 0) return 1; if (difference.numerator < 0) return -1; else return 0; } #endregion } }