source: trunk/abcl/src/org/armedbear/lisp/Ratio.java

Last change on this file was 15569, checked in by Mark Evenson, 2 years ago

Untabify en masse

Results of running style.org source blocks on tree

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 20.0 KB
Line 
1/*
2 * Ratio.java
3 *
4 * Copyright (C) 2003-2005 Peter Graves
5 * $Id: Ratio.java 15569 2022-03-19 12:50:18Z mevenson $
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20 *
21 * As a special exception, the copyright holders of this library give you
22 * permission to link this library with independent modules to produce an
23 * executable, regardless of the license terms of these independent
24 * modules, and to copy and distribute the resulting executable under
25 * terms of your choice, provided that you also meet, for each linked
26 * independent module, the terms and conditions of the license of that
27 * module.  An independent module is a module which is not derived from
28 * or based on this library.  If you modify this library, you may extend
29 * this exception to your version of the library, but you are not
30 * obligated to do so.  If you do not wish to do so, delete this
31 * exception statement from your version.
32 */
33
34package org.armedbear.lisp;
35
36import static org.armedbear.lisp.Lisp.*;
37
38import java.math.BigInteger;
39import java.math.BigDecimal;
40import java.math.MathContext;
41import java.math.RoundingMode;
42
43public final class Ratio extends LispObject
44{
45    private BigInteger numerator;
46    private BigInteger denominator;
47
48    public Ratio(BigInteger numerator, BigInteger denominator)
49    {
50        this.numerator = numerator;
51        this.denominator = denominator;
52    }
53
54    public BigInteger numerator()
55    {
56        return numerator;
57    }
58
59    @Override
60    public LispObject NUMERATOR()
61    {
62        return number(numerator);
63    }
64
65    public BigInteger denominator()
66    {
67        return denominator;
68    }
69
70    @Override
71    public LispObject DENOMINATOR()
72    {
73        return number(denominator);
74    }
75
76    @Override
77    public LispObject typeOf()
78    {
79        return Symbol.RATIO;
80    }
81
82    @Override
83    public LispObject classOf()
84    {
85        return BuiltInClass.RATIO;
86    }
87
88    @Override
89    public LispObject typep(LispObject type)
90    {
91        if (type == Symbol.RATIO)
92            return T;
93        if (type == Symbol.RATIONAL)
94            return T;
95        if (type == Symbol.REAL)
96            return T;
97        if (type == Symbol.NUMBER)
98            return T;
99        if (type == BuiltInClass.RATIO)
100            return T;
101        return super.typep(type);
102    }
103
104    @Override
105    public boolean numberp()
106    {
107        return true;
108    }
109
110    @Override
111    public boolean rationalp()
112    {
113        return true;
114    }
115
116    @Override
117    public boolean realp()
118    {
119        return true;
120    }
121
122    @Override
123    public boolean eql(LispObject obj)
124    {
125        if (this == obj)
126            return true;
127        if (obj instanceof Ratio) {
128            return (numerator.equals(((Ratio)obj).numerator) &&
129                    denominator.equals(((Ratio)obj).denominator));
130        }
131        return false;
132    }
133
134    @Override
135    public boolean equal(LispObject obj)
136    {
137        return eql(obj);
138    }
139
140    @Override
141    public boolean equalp(LispObject obj)
142    {
143        if (obj != null && obj.numberp())
144            return isEqualTo(obj);
145        return false;
146    }
147
148    @Override
149    public LispObject ABS()
150    {
151        if (numerator.signum() > 0 && denominator.signum() > 0)
152            return this;
153        if (numerator.signum() < 0 && denominator.signum() < 0)
154            return this;
155        return new Ratio(numerator.negate(), denominator);
156    }
157
158    @Override
159    public boolean plusp()
160    {
161        return numerator.signum() == denominator.signum();
162    }
163
164    @Override
165    public boolean minusp()
166    {
167        return numerator.signum() != denominator.signum();
168    }
169
170    @Override
171    public boolean zerop()
172    {
173        return false;
174    }
175
176    @Override
177    public float floatValue()
178    {
179        float result = (float) doubleValue();
180        if (Float.isInfinite(result) && TRAP_OVERFLOW)
181            type_error(this, Symbol.SINGLE_FLOAT);
182
183        return (float) doubleValue();
184    }
185
186    @Override
187    public double doubleValue()
188    {
189        double result = numerator.doubleValue() / denominator.doubleValue();
190        if (result != 0 && !Double.isNaN(result) && !Double.isInfinite(result))
191            return result;
192        final boolean negative = numerator.signum() < 0;
193        final BigInteger num = negative ? numerator.negate() : numerator;
194        final BigInteger den = denominator;
195        final int numLen = num.bitLength();
196        final int denLen = den.bitLength();
197        int length = Math.min(numLen, denLen);
198        if (length <= 1) {
199          // A precision of 512 is overkill for DOUBLE-FLOAT types
200          // based on java.lang.Double  TODO: optimize for space/time
201          final MathContext mathContext = new MathContext(512, RoundingMode.HALF_EVEN);
202          BigDecimal p = new BigDecimal(numerator, mathContext);
203          BigDecimal q = new BigDecimal(denominator, mathContext);
204          BigDecimal r = p.divide(q, mathContext);
205          result = r.doubleValue();
206          return result;
207        }
208
209        BigInteger n = num;
210        BigInteger d = den;
211        final int digits = 54;
212        if (length > digits) {
213            n = n.shiftRight(length - digits);
214            d = d.shiftRight(length - digits);
215            length -= digits;
216        } else {
217            n = n.shiftRight(1);
218            d = d.shiftRight(1);
219            --length;
220        }
221        for (int i = 0; i < length; i++) {
222            result = n.doubleValue() / d.doubleValue();
223            if (result != 0 && !Double.isNaN(result) && !Double.isInfinite(result))
224                break;
225            n = n.shiftRight(1);
226            d = d.shiftRight(1);
227        }
228        if (Double.isInfinite(result) && TRAP_OVERFLOW)
229            type_error(this, Symbol.DOUBLE_FLOAT);
230
231        return negative ? -result : result;
232    }
233
234    @Override
235    public final LispObject incr()
236    {
237        return new Ratio(numerator.add(denominator), denominator);
238    }
239
240    @Override
241    public final LispObject decr()
242    {
243        return new Ratio(numerator.subtract(denominator), denominator);
244    }
245
246    @Override
247    public LispObject add(LispObject obj)
248    {
249        if (obj instanceof Fixnum) {
250            BigInteger n =
251                numerator.add(BigInteger.valueOf(((Fixnum)obj).value).multiply(denominator));
252            return number(n, denominator);
253        }
254        if (obj instanceof Bignum) {
255            BigInteger n = ((Bignum)obj).value;
256            return number(numerator.add(n.multiply(denominator)),
257                denominator);
258        }
259        if (obj instanceof Ratio) {
260            BigInteger n = ((Ratio)obj).numerator;
261            BigInteger d = ((Ratio)obj).denominator;
262            if (denominator.equals(d))
263                return number(numerator.add(n), denominator);
264            BigInteger common = denominator.multiply(d);
265            return number(numerator.multiply(d).add(n.multiply(denominator)),
266                common);
267        }
268        if (obj instanceof SingleFloat) {
269            return new SingleFloat(floatValue() + ((SingleFloat)obj).value);
270        }
271        if (obj instanceof DoubleFloat) {
272            return new DoubleFloat(doubleValue() + ((DoubleFloat)obj).value);
273        }
274        if (obj instanceof Complex) {
275            Complex c = (Complex) obj;
276            return Complex.getInstance(add(c.getRealPart()), c.getImaginaryPart());
277        }
278        return type_error(obj, Symbol.NUMBER);
279    }
280
281    @Override
282    public LispObject subtract(LispObject obj)
283    {
284        if (obj instanceof Fixnum) {
285            BigInteger n =
286                numerator.subtract(BigInteger.valueOf(((Fixnum)obj).value).multiply(denominator));
287            return number(n, denominator);
288        }
289        if (obj instanceof Bignum) {
290            BigInteger n = ((Bignum)obj).value;
291            return number(numerator.subtract(n.multiply(denominator)),
292                denominator);
293        }
294        if (obj instanceof Ratio) {
295            BigInteger n = ((Ratio)obj).numerator;
296            BigInteger d = ((Ratio)obj).denominator;
297            if (denominator.equals(d))
298                return number(numerator.subtract(n), denominator);
299            BigInteger common = denominator.multiply(d);
300            return number(numerator.multiply(d).subtract(n.multiply(denominator)),
301                common);
302        }
303        if (obj instanceof SingleFloat) {
304            return new SingleFloat(floatValue() - ((SingleFloat)obj).value);
305        }
306        if (obj instanceof DoubleFloat) {
307            return new DoubleFloat(doubleValue() - ((DoubleFloat)obj).value);
308        }
309        if (obj instanceof Complex) {
310            Complex c = (Complex) obj;
311            return Complex.getInstance(subtract(c.getRealPart()),
312                                       Fixnum.ZERO.subtract(c.getImaginaryPart()));
313        }
314        return type_error(obj, Symbol.NUMBER);
315    }
316
317    @Override
318    public LispObject multiplyBy(LispObject obj)
319    {
320        if (obj instanceof Fixnum) {
321            BigInteger n = ((Fixnum)obj).getBigInteger();
322            return number(numerator.multiply(n), denominator);
323        }
324        if (obj instanceof Bignum) {
325            BigInteger n = ((Bignum)obj).value;
326            return number(numerator.multiply(n), denominator);
327        }
328        if (obj instanceof Ratio) {
329            BigInteger n = ((Ratio)obj).numerator;
330            BigInteger d = ((Ratio)obj).denominator;
331            return number(numerator.multiply(n), denominator.multiply(d));
332        }
333        if (obj instanceof SingleFloat) {
334            return new SingleFloat(floatValue() * ((SingleFloat)obj).value);
335        }
336        if (obj instanceof DoubleFloat) {
337            return new DoubleFloat(doubleValue() * ((DoubleFloat)obj).value);
338        }
339        if (obj instanceof Complex) {
340            Complex c = (Complex) obj;
341            return Complex.getInstance(multiplyBy(c.getRealPart()),
342                                       multiplyBy(c.getImaginaryPart()));
343        }
344        return type_error(obj, Symbol.NUMBER);
345    }
346
347    @Override
348    public LispObject divideBy(LispObject obj)
349    {
350        if (obj.zerop()) {
351          LispObject operands = new Cons(this, new Cons(obj));
352          LispObject args = new Cons(Keyword.OPERATION,
353                                     new Cons(Symbol.SLASH,
354                                              new Cons(Keyword.OPERANDS,
355                                                       new Cons(operands))));
356          return error(new DivisionByZero(args));
357        }
358
359        if (obj instanceof Fixnum) {
360            BigInteger n = ((Fixnum)obj).getBigInteger();
361            return number(numerator, denominator.multiply(n));
362        }
363        if (obj instanceof Bignum) {
364            BigInteger n = ((Bignum)obj).value;
365            return number(numerator, denominator.multiply(n));
366        }
367        if (obj instanceof Ratio) {
368            BigInteger n = ((Ratio)obj).numerator;
369            BigInteger d = ((Ratio)obj).denominator;
370            return number(numerator.multiply(d), denominator.multiply(n));
371        }
372        if (obj instanceof SingleFloat) {
373            return new SingleFloat(floatValue() / ((SingleFloat)obj).value);
374        }
375        if (obj instanceof DoubleFloat) {
376            return new DoubleFloat(doubleValue() / ((DoubleFloat)obj).value);
377        }
378        if (obj instanceof Complex) {
379            Complex c = (Complex) obj;
380            // numerator
381            LispObject realPart = this.multiplyBy(c.getRealPart());
382            LispObject imagPart =
383                Fixnum.ZERO.subtract(this).multiplyBy(c.getImaginaryPart());
384            // denominator
385            LispObject d =
386                c.getRealPart().multiplyBy(c.getRealPart());
387            d = d.add(c.getImaginaryPart().multiplyBy(c.getImaginaryPart()));
388            return Complex.getInstance(realPart.divideBy(d),
389                                       imagPart.divideBy(d));
390        }
391        return type_error(obj, Symbol.NUMBER);
392    }
393
394    @Override
395    public boolean isEqualTo(LispObject obj)
396    {
397        if (obj instanceof Ratio)
398            return (numerator.equals(((Ratio)obj).numerator) &&
399                    denominator.equals(((Ratio)obj).denominator));
400        if (obj instanceof SingleFloat)
401            return isEqualTo(((SingleFloat)obj).rational());
402        if (obj instanceof DoubleFloat)
403            return isEqualTo(((DoubleFloat)obj).rational());
404        if (obj.numberp())
405            return false;
406        type_error(obj, Symbol.NUMBER);
407        // Not reached.
408        return false;
409    }
410
411    @Override
412    public boolean isNotEqualTo(LispObject obj)
413    {
414        return !isEqualTo(obj);
415    }
416
417    @Override
418    public boolean isLessThan(LispObject obj)
419    {
420        if (obj instanceof Fixnum) {
421            BigInteger n2 = ((Fixnum)obj).getBigInteger().multiply(denominator);
422            return numerator.compareTo(n2) < 0;
423        }
424        if (obj instanceof Bignum) {
425            BigInteger n = ((Bignum)obj).value.multiply(denominator);
426            return numerator.compareTo(n) < 0;
427        }
428        if (obj instanceof Ratio) {
429            BigInteger n1 = numerator.multiply(((Ratio)obj).denominator);
430            BigInteger n2 = ((Ratio)obj).numerator.multiply(denominator);
431            return n1.compareTo(n2) < 0;
432        }
433        if (obj instanceof SingleFloat)
434            return isLessThan(((SingleFloat)obj).rational());
435        if (obj instanceof DoubleFloat)
436            return isLessThan(((DoubleFloat)obj).rational());
437        type_error(obj, Symbol.REAL);
438        // Not reached.
439        return false;
440    }
441
442    @Override
443    public boolean isGreaterThan(LispObject obj)
444    {
445        if (obj instanceof Fixnum) {
446            BigInteger n2 = ((Fixnum)obj).getBigInteger().multiply(denominator);
447            return numerator.compareTo(n2) > 0;
448        }
449        if (obj instanceof Bignum) {
450            BigInteger n = ((Bignum)obj).value.multiply(denominator);
451            return numerator.compareTo(n) > 0;
452        }
453        if (obj instanceof Ratio) {
454            BigInteger n1 = numerator.multiply(((Ratio)obj).denominator);
455            BigInteger n2 = ((Ratio)obj).numerator.multiply(denominator);
456            return n1.compareTo(n2) > 0;
457        }
458        if (obj instanceof SingleFloat)
459            return isGreaterThan(((SingleFloat)obj).rational());
460        if (obj instanceof DoubleFloat)
461            return isGreaterThan(((DoubleFloat)obj).rational());
462        type_error(obj, Symbol.REAL);
463        // Not reached.
464        return false;
465    }
466
467    @Override
468    public boolean isLessThanOrEqualTo(LispObject obj)
469    {
470        if (obj instanceof Fixnum) {
471            BigInteger n2 = ((Fixnum)obj).getBigInteger().multiply(denominator);
472            return numerator.compareTo(n2) <= 0;
473        }
474        if (obj instanceof Bignum) {
475            BigInteger n = ((Bignum)obj).value.multiply(denominator);
476            return numerator.compareTo(n) <= 0;
477        }
478        if (obj instanceof Ratio) {
479            BigInteger n1 = numerator.multiply(((Ratio)obj).denominator);
480            BigInteger n2 = ((Ratio)obj).numerator.multiply(denominator);
481            return n1.compareTo(n2) <= 0;
482        }
483        if (obj instanceof SingleFloat)
484            return isLessThanOrEqualTo(((SingleFloat)obj).rational());
485        if (obj instanceof DoubleFloat)
486            return isLessThanOrEqualTo(((DoubleFloat)obj).rational());
487        type_error(obj, Symbol.REAL);
488        // Not reached.
489        return false;
490    }
491
492    @Override
493    public boolean isGreaterThanOrEqualTo(LispObject obj)
494    {
495        if (obj instanceof Fixnum) {
496            BigInteger n2 = ((Fixnum)obj).getBigInteger().multiply(denominator);
497            return numerator.compareTo(n2) >= 0;
498        }
499        if (obj instanceof Bignum) {
500            BigInteger n = ((Bignum)obj).value.multiply(denominator);
501            return numerator.compareTo(n) >= 0;
502        }
503        if (obj instanceof Ratio) {
504            BigInteger n1 = numerator.multiply(((Ratio)obj).denominator);
505            BigInteger n2 = ((Ratio)obj).numerator.multiply(denominator);
506            return n1.compareTo(n2) >= 0;
507        }
508        if (obj instanceof SingleFloat)
509            return isGreaterThanOrEqualTo(((SingleFloat)obj).rational());
510        if (obj instanceof DoubleFloat)
511            return isGreaterThanOrEqualTo(((DoubleFloat)obj).rational());
512        type_error(obj, Symbol.REAL);
513        // Not reached.
514        return false;
515    }
516
517    @Override
518    public LispObject truncate(LispObject obj)
519    {
520        // "When rationals and floats are combined by a numerical function,
521        // the rational is first converted to a float of the same format."
522        // 12.1.4.1
523        if (obj instanceof SingleFloat)
524            return new SingleFloat(floatValue()).truncate(obj);
525        if (obj instanceof DoubleFloat)
526            return new DoubleFloat(doubleValue()).truncate(obj);
527        BigInteger n, d;
528        try {
529          if (obj instanceof Fixnum) {
530            n = ((Fixnum)obj).getBigInteger();
531            d = BigInteger.ONE;
532          } else if (obj instanceof Bignum) {
533            n = ((Bignum)obj).value;
534            d = BigInteger.ONE;
535          } else if (obj instanceof Ratio) {
536            n = ((Ratio)obj).numerator();
537            d = ((Ratio)obj).denominator();
538          } else {
539            return type_error(obj, Symbol.NUMBER);
540          }
541          // Invert and multiply.
542          BigInteger num = numerator.multiply(d);
543          BigInteger den = denominator.multiply(n);
544          BigInteger quotient = num.divide(den);
545          // Multiply quotient by divisor.
546          LispObject product = number(quotient.multiply(n), d);
547          // Subtract to get remainder.
548          LispObject remainder = subtract(product);
549          return LispThread.currentThread().setValues(number(quotient), remainder);
550        }
551        catch (ArithmeticException e) {
552            if (obj.zerop()) {
553              LispObject operands = new Cons(this, new Cons(obj));
554              LispObject args = new Cons(Keyword.OPERATION,
555                                         new Cons(Symbol.TRUNCATE,
556                                                  new Cons(Keyword.OPERANDS,
557                                                           new Cons(operands))));
558              return error(new DivisionByZero(args));
559            }
560            return error(new ArithmeticError(e.getMessage()));
561        }
562    }
563
564    @Override
565    public int hashCode()
566    {
567        return numerator.hashCode() ^ denominator.hashCode();
568    }
569
570    @Override
571    public String printObject()
572    {
573        final LispThread thread = LispThread.currentThread();
574        int base = Fixnum.getValue(Symbol.PRINT_BASE.symbolValue(thread));
575        StringBuffer sb = new StringBuffer(numerator.toString(base));
576        sb.append('/');
577        sb.append(denominator.toString(base));
578        String s = sb.toString().toUpperCase();
579        if (Symbol.PRINT_RADIX.symbolValue(thread) != NIL) {
580            sb.setLength(0);
581            switch (base) {
582                case 2:
583                    sb.append("#b");
584                    sb.append(s);
585                    break;
586                case 8:
587                    sb.append("#o");
588                    sb.append(s);
589                    break;
590                case 10:
591                    sb.append("#10r");
592                    sb.append(s);
593                    break;
594                case 16:
595                    sb.append("#x");
596                    sb.append(s);
597                    break;
598                default:
599                    sb.append('#');
600                    sb.append(String.valueOf(base));
601                    sb.append('r');
602                    sb.append(s);
603                    break;
604            }
605            s = sb.toString();
606        }
607        return s;
608    }
609}
Note: See TracBrowser for help on using the repository browser.