📄 firational.cs
字号:
// ==========================================================
// 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.3 $
// $Date: 2008/06/16 15:17:37 $
// $Id: FIRational.cs,v 1.3 2008/06/16 15:17:37 cklein05 Exp $
// ==========================================================
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace FreeImageAPI
{
/// <summary>
/// The <b>FIRational</b> structure represents a fraction via two <see cref="Int32"/>
/// instances which are interpreted as numerator and denominator.
/// </summary>
/// <remarks>
/// The structure tries to approximate the value of <see cref="FreeImageAPI.FIRational(decimal)"/>
/// when creating a new instance by using a better algorithm than FreeImage does.
/// <para/>
/// The structure implements the following operators:
/// +, -, ++, --, ==, != , >, >==, <, <== and ~ (which switches nominator and denomiator).
/// <para/>
/// The structure can be converted into all .NET standard types either implicit or
/// explicit.
/// </remarks>
[Serializable, StructLayout(LayoutKind.Sequential), ComVisible(true)]
public struct FIRational : IConvertible, IComparable, IFormattable, IComparable<FIRational>, IEquatable<FIRational>
{
private int numerator;
private int denominator;
/// <summary>
/// Represents the largest possible value of <see cref="FIRational"/>. This field is constant.
/// </summary>
public static readonly FIRational MaxValue = new FIRational(Int32.MaxValue, 1);
/// <summary>
/// Represents the smallest possible value of <see cref="FIRational"/>. This field is constant.
/// </summary>
public static readonly FIRational MinValue = new FIRational(Int32.MinValue, 1);
/// <summary>
/// Represents the smallest positive <see cref="FIRational"/> value greater than zero. This field is constant.
/// </summary>
public static readonly FIRational Epsilon = new FIRational(1, Int32.MaxValue);
/// <summary>
/// Initializes a new instance based on the specified parameters.
/// </summary>
/// <param name="n">The numerator.</param>
/// <param name="d">The denominator.</param>
public FIRational(int n, int d)
{
numerator = n;
denominator = d;
Normalize();
}
/// <summary>
/// Initializes a new instance based on the specified parameters.
/// </summary>
/// <param name="tag">The tag to read the data from.</param>
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");
}
}
/// <summary>
/// Initializes a new instance based on the specified parameters.
/// </summary>
/// <param name="value">The value to convert into a fraction.</param>
/// <exception cref="OverflowException">
/// <paramref name="value"/> cannot be converted into a fraction
/// represented by two integer values.</exception>
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();
}
}
numerator *= sign;
Normalize();
}
catch (Exception ex)
{
throw new OverflowException("Unable to calculate fraction.", ex);
}
}
/// <summary>
/// Initializes a new instance based on the specified parameters.
/// </summary>
/// <param name="r">The structure to clone from.</param>
public FIRational(FIRational r)
{
numerator = r.numerator;
denominator = r.denominator;
Normalize();
}
/// <summary>
/// The numerator of the fraction.
/// </summary>
public int Numerator
{
get { return numerator; }
}
/// <summary>
/// The denominator of the fraction.
/// </summary>
public int Denominator
{
get { return denominator; }
}
/// <summary>
/// Returns the truncated value of the fraction.
/// </summary>
/// <returns></returns>
public int Truncate()
{
return denominator > 0 ? (int)(numerator / denominator) : 0;
}
/// <summary>
/// Returns whether the fraction is representing an integer value.
/// </summary>
public bool IsInteger
{
get
{
return (denominator == 1 ||
(denominator != 0 && (numerator % denominator == 0)) ||
(denominator == 0 && numerator == 0));
}
}
/// <summary>
/// Calculated the greatest common divisor of 'a' and 'b'.
/// </summary>
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;
}
/// <summary>
/// Calculated the smallest common multiple of 'a' and 'b'.
/// </summary>
private static long Scm(int n, int m)
{
return Math.Abs((long)n * (long)m) / Gcd(n, m);
}
/// <summary>
/// Normalizes the fraction.
/// </summary>
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;
}
}
/// <summary>
/// Normalizes a fraction.
/// </summary>
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;
}
}
/// <summary>
/// Returns the digits after the point.
/// </summary>
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;
}
/// <summary>
/// Creates a continued fraction of a decimal value.
/// </summary>
private static int[] CreateContinuedFraction(decimal value)
{
int precision = GetDigits(value);
decimal epsilon = 0.0000001m;
List<int> list = new List<int>();
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();
}
/// <summary>
/// Creates a fraction from a continued fraction.
/// </summary>
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;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -