私は2次方程式ソルバーを作成するプロジェクトを開始しました。私の次のステップは、X とX などの値を変換することである。(X + X 1)(X + X 2)正確な分数に、それらが小数になる場合。小数点から偶数の小数点の変換をC#
だから例である:
12X + 44X + 21
は私を与える、
X = -3.10262885097732
X = -0.564037815689349
しかし、これを正確な分数にどのように変換できますか? 助けてくれてありがとう!
私は2次方程式ソルバーを作成するプロジェクトを開始しました。私の次のステップは、X とX などの値を変換することである。(X + X 1)(X + X 2)正確な分数に、それらが小数になる場合。小数点から偶数の小数点の変換をC#
だから例である:
12X + 44X + 21
は私を与える、
X = -3.10262885097732
X = -0.564037815689349
しかし、これを正確な分数にどのように変換できますか? 助けてくれてありがとう!
Continued Fractionsを使用してこの問題を解決できます。
コメントに記載されているように、ちょうどirrational numberを表す端数(rational number)は取得できませんが、かなり近づくことがあります。
私はpetプロジェクトで有理数型を一度実装しました。あなたはそれを見つけることができますhere。継続分数を使用して任意の数値に最も近い有理数(指定された精度で)を取得する方法の例については、TryFromDouble
を参照してください。
関連するコードの抜粋は以下の(それは長すぎるので、私は 全タイプの実装を掲載しませんが、コードはまだかなり理解できなければならない)である:アルゴリズム[の
public static bool TryFromDouble(double target, double precision, out Rational result)
{
//Continued fraction algorithm: http://en.wikipedia.org/wiki/Continued_fraction
//Implemented recursively. Problem is figuring out when precision is met without unwinding each solution. Haven't figured out how to do that.
//Current implementation computes rational number approximations for increasing algorithm depths until precision criteria is met, maximum depth is reached (fromDoubleMaxIterations)
//or an OverflowException is thrown. Efficiency is probably improvable but this method will not be used in any performance critical code. No use in optimizing it unless there is
//a good reason. Current implementation works reasonably well.
result = zero;
int steps = 0;
while (Math.Abs(target - Rational.ToDouble(result)) > precision)
{
if (steps > fromDoubleMaxIterations)
{
result = zero;
return false;
}
result = getNearestRationalNumber(target, 0, steps++);
}
return true;
}
private static Rational getNearestRationalNumber(double number, int currentStep, int maximumSteps)
{
var integerPart = (BigInteger)number;
double fractionalPart = number - Math.Truncate(number);
while (currentStep < maximumSteps && fractionalPart != 0)
{
return integerPart + new Rational(1, getNearestRationalNumber(1/fractionalPart, ++currentStep, maximumSteps));
}
return new Rational(integerPart);
}
ありがとうございました!!! –
可能な複製のために小数点以下を簡素化する](http://stackoverflow.com/questions/5124743/algorithm-for-simplifying-decimal-to-fractions) – Adrian
これらはどちらも非合理的な数字です。それらを表す正確な分数はありません。 – JLRishe
多分あなたはここで役に立つ何かを見つけることができます:http://stackoverflow.com/questions/5124743/algorithm-for-simplifying-decimal-to-fractions –