📄 fiurational.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: FIURational.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>FIURational</b> structure represents a fraction via two <see cref="UInt32"/>
/// instances which are interpreted as numerator and denominator.
/// </summary>
/// <remarks>
/// The structure tries to approximate the value of <see cref="FreeImageAPI.FIURational(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 FIURational : IConvertible, IComparable, IFormattable, IComparable<FIURational>, IEquatable<FIURational>
{
private uint numerator;
private uint denominator;
/// <summary>
/// Represents the largest possible value of <see cref="FIURational"/>. This field is constant.
/// </summary>
public static readonly FIURational MaxValue = new FIURational(UInt32.MaxValue, 1u);
/// <summary>
/// Represents the smallest possible value of <see cref="FIURational"/>. This field is constant.
/// </summary>
public static readonly FIURational MinValue = new FIURational(0u, 1u);
/// <summary>
/// Represents the smallest positive <see cref="FIURational"/> value greater than zero. This field is constant.
/// </summary>
public static readonly FIURational Epsilon = new FIURational(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 FIURational(uint n, uint 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 FIURational(FITAG tag)
{
switch (FreeImage.GetTagType(tag))
{
case FREE_IMAGE_MDTYPE.FIDT_RATIONAL:
uint* pvalue = (uint*)FreeImage.GetTagValue(tag);
numerator = pvalue[0];
denominator = pvalue[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 FIURational(decimal value)
{
try
{
if (value < 0) throw new ArgumentOutOfRangeException("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();
}
}
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 FIURational(FIURational r)
{
numerator = r.numerator;
denominator = r.denominator;
Normalize();
}
/// <summary>
/// The numerator of the fraction.
/// </summary>
public uint Numerator
{
get { return numerator; }
}
/// <summary>
/// The denominator of the fraction.
/// </summary>
public uint 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 ulong Gcd(ulong a, ulong b)
{
ulong 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 ulong Scm(uint n, uint m)
{
return (ulong)n * (ulong)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)
{
uint common = (uint)Gcd(numerator, denominator);
if (common != 1 && common != 0)
{
numerator /= common;
denominator /= common;
}
}
}
/// <summary>
/// Normalizes a fraction.
/// </summary>
private static void Normalize(ref ulong numerator, ref ulong denominator)
{
if (denominator == 0)
{
numerator = 0;
denominator = 1;
}
else if (numerator != 1 && denominator != 1)
{
ulong common = Gcd(numerator, denominator);
if (common != 1)
{
numerator /= common;
denominator /= common;
}
}
}
/// <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 uint numerator, out uint denominator)
{
numerator = 1;
denominator = 0;
uint temp;
for (int i = continuedFraction.Length - 1; i > -1; i--)
{
temp = numerator;
numerator = (uint)(continuedFraction[i] * numerator + denominator);
denominator = temp;
}
}
/// <summary>
/// Tries 'brute force' to approximate <paramref name="value"/> with a fraction.
/// </summary>
private static void ApproximateFraction(decimal value, int maxDen, out uint num, out uint den)
{
num = 0;
den = 0;
decimal bestDifference = 1m;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -