Java Reference
In-Depth Information
1 public BigRational( BigInteger n, BigInteger d )
2 {
3 num = n; den = d;
4 check00( ); fixSigns( ); reduce( );
5 }
6
7 public BigRational( String str )
8 {
9 if( str.length( ) == 0 )
10 throw new IllegalArgumentException( "Zero-length string" );
11
12 // Check for '/'
13 int slashIndex = str.indexOf( '/' );
14 if( slashIndex == -1 )
15 {
16
num = new BigInteger( str.trim( ) );
den = BigInteger.ONE; // no denominator... use 1
17
18 }
19 else
20 {
21 num = new BigInteger( str.substring( 0, slashIndex ).trim( ) );
22 den = new BigInteger( str.substring( slashIndex + 1 ).trim( ) );
23 check00( ); fixSigns( ); reduce( );
24 }
25 }
26
27 private void check00( )
28 {
29 if( num.equals( BigInteger.ZERO ) && den.equals( BigInteger.ZERO ) )
30 throw new ArithmeticException( "ZERO DIVIDE BY ZERO" );
31 }
32
33 private void fixSigns( )
34 {
35 if( den.compareTo( BigInteger.ZERO ) < 0 )
36 {
37 num = num.negate( );
38 den = den.negate( );
39 }
40 }
41
42 private void reduce( )
43 {
44 BigInteger gcd = num.gcd( den );
45 num = num.divide( gcd );
46 den = den.divide( gcd );
47 }
figure 3.12
BigRational constructors, check00 , fixSigns , and reduce
Search WWH ::




Custom Search