我正在尝试使用Java中的分数.
我想实现算术函数.为此,我首先要求一种方法来规范化功能.我知道我不能加1/6和1/2,直到我有一个共同点.我将不得不添加1/6和3/6.一个天真的方法会让我添加2/12和6/12,然后减少.如何实现性能损失最小的共同点?什么算法最适合这个?
版本8(感谢hstoerr):
改进包括:
- equals()方法现在与compareTo()方法一致
final class Fraction extends Number {
private int numerator;
private int denominator;
public Fraction(int numerator, int denominator) {
if(denominator == 0) {
throw new IllegalArgumentException("denominator is zero");
}
if(denominator < 0) {
numerator *= -1;
denominator *= -1;
}
this.numerator = numerator;
this.denominator = denominator;
}
public Fraction(int numerator) {
this.numerator = numerator;
this.denominator = 1;
}
public int getNumerator() {
return this.numerator;
}
public int getDenominator() {
return this.denominator;
} …Run Code Online (Sandbox Code Playgroud) 我需要找到一个浮点数与另一个浮点数的比率,该比率需要是两个整数.例如:
1.5, 3.25"6:13"有谁知道吗?在互联网上搜索,我没有找到这样的算法,也没有找到两个浮点数(只是整数)的最小公倍数或分母的算法.
这是我将使用的最终实现:
public class RatioTest
{
public static String getRatio(double d1, double d2)//1.5, 3.25
{
while(Math.max(d1,d2) < Long.MAX_VALUE && d1 != (long)d1 && d2 != (long)d2)
{
d1 *= 10;//15 -> 150
d2 *= 10;//32.5 -> 325
}
//d1 == 150.0
//d2 == 325.0
try
{
double gcd = getGCD(d1,d2);//gcd == 25
return ((long)(d1 / gcd)) + ":" + ((long)(d2 / gcd));//"6:13"
}
catch (StackOverflowError er)//in case getGDC (a recursively looping method) repeats …Run Code Online (Sandbox Code Playgroud) 最近,一位记者提到float.as_integer_ratio()了Python 2.6中的新内容,指出典型的浮点实现基本上是实数的有理近似.好奇,我不得不尝试π:
>>> float.as_integer_ratio(math.pi);
(884279719003555L, 281474976710656L)
Run Code Online (Sandbox Code Playgroud)
(428224593349304L, 136308121570117L)
Run Code Online (Sandbox Code Playgroud)
例如,这段代码:
#! /usr/bin/env python
from decimal import *
getcontext().prec = 36
print "python: ",Decimal(884279719003555) / Decimal(281474976710656)
print "Arima: ",Decimal(428224593349304) / Decimal(136308121570117)
print "Wiki: 3.14159265358979323846264338327950288"
Run Code Online (Sandbox Code Playgroud)
产生这个输出:
python: 3.14159265358979311599796346854418516 Arima: 3.14159265358979323846264338327569743 Wiki: 3.14159265358979323846264338327950288
当然,考虑到64位浮点数提供的精度,结果是正确的,但它让我问:我怎样才能找到更多有关实现限制的结果 as_integer_ratio()?谢谢你的指导.
其他链接:Stern-Brocot树和Python源代码.