我有一个双输入“ a”。我的目标是找到一个整数“ b”,这样“ a * b”将产生一个整数,加上一些允许的误差。例如“ 100.227273 * 22 = 2205(+ 0.000006错误)”,我要查找的答案是“ 22”。
我已经研究过this post,但我仅部分理解了最佳答案。我真的可以使用一些帮助来创建完成该任务的算法。我下面有一些适用于某些情况的代码,但不是全部。
private int FindSmallestMultiplier(double input)
{
int numerator = 1;
int temp;
double output = input;
double invert = input;
int denominator = 1;
List<int> whole = new List<int>();
double dec = input;
int i = -1;
while (Math.Abs(Math.Round(numerator * input)-numerator*input) > 0.001)
{
i = i + 1;
//seperate out the whole and decimal portions of the input
whole.Add(Convert.ToInt32(Math.Floor(invert)));
dec = output - whole[i];
//get the decimal portion of the input, and invert
invert = 1 / dec;
//create nested fraction to determine how far off from a whole integer we are
denominator = 1;
numerator = 1;
for(int j = whole.Count-1; j >= 0; j--)
{
temp = whole[j] * denominator + numerator;
numerator = denominator;
denominator = temp;
}
}
return numerator;
}
上面的代码适用于许多输入情况,例如0.3333、0.5。一个不起作用的示例是0.75或0.101,只是为了将对命名为无穷大。请帮助我弄清楚我的代码有什么问题,或者提供一个可以产生预期结果的代码示例。谢谢!
答案 0 :(得分:2)
这是链接的问题中描述的方法的示例实现。如果迭代计算连续分数的新系数。这样做,它检查重构的数字是否达到所需的精度。如果是这样,它将返回重构分数的分母作为结果
// Reconstructs a fraction from a continued fraction with the given coefficients
static Tuple<int, int> ReconstructContinuedFraction(List<int> coefficients)
{
int numerator = coefficients.Last();
int denominator = 1;
for(int i = coefficients.Count - 2; i >= 0; --i)
{
//swap numerator and denominator (= invert number)
var temp = numerator;
numerator = denominator;
denominator = temp;
numerator += denominator * coefficients[i];
}
return new Tuple<int, int>(numerator, denominator);
}
static int FindSmallestMultiplier(double input, double error)
{
double remainingToRepresent = input;
List<int> coefficients = new List<int>();
while (true)
{
//calculate the next coefficient
var integer = (int)Math.Floor(remainingToRepresent);
remainingToRepresent -= integer;
remainingToRepresent = 1 / remainingToRepresent;
coefficients.Add(integer);
//check if we reached the desired accuracy
var reconstructed = ReconstructContinuedFraction(coefficients);
var multipliedInput = input * reconstructed.Item2;
var multipliedInputRounded = Math.Round(multipliedInput);
if (Math.Abs(multipliedInput - multipliedInputRounded) < error)
return reconstructed.Item2;
}
}
一个示例程序,尝试找到Pi的乘数...
public static void Main()
{
var number = Math.PI;
var multiplier = FindSmallestMultiplier(number, 0.001);
Console.WriteLine(number + " * " + multiplier + " = " + number * multiplier);
}
...给出以下输出:
3.14159265358979 * 113 = 354.999969855647