Changes in src/libcfa/rational.c [630a82a:3d9b5da]
- File:
-
- 1 edited
-
src/libcfa/rational.c (modified) (10 diffs)
Legend:
- Unmodified
- Added
- Removed
-
src/libcfa/rational.c
r630a82a r3d9b5da 11 11 // Created On : Wed Apr 6 17:54:28 2016 12 12 // Last Modified By : Peter A. Buhr 13 // Last Modified On : Fri Apr 8 15:39:17201614 // Update Count : 1 713 // Last Modified On : Thu Apr 7 17:28:03 2016 14 // Update Count : 12 15 15 // 16 16 … … 23 23 } // extern 24 24 25 26 // constants27 28 25 struct Rational 0 = {0, 1}; 29 26 struct Rational 1 = {1, 1}; 30 27 31 32 // helper 33 34 // Calculate greatest common denominator of two numbers, the first of which may be negative. Used to reduce rationals. 35 static long int gcd( long int a, long int b ) { 28 // Calculate the greatest common denominator of two numbers, the first of which may be negative. It is used to reduce 29 // rationals. 30 31 long int gcd( long int a, long int b ) { 36 32 for ( ;; ) { // Euclid's algorithm 37 33 long int r = a % b; … … 43 39 } // gcd 44 40 45 staticlong int simplify( long int *n, long int *d ) {41 long int simplify( long int *n, long int *d ) { 46 42 if ( *d == 0 ) { 47 43 serr | "Invalid rational number construction: denominator cannot be equal to 0." | endl; … … 52 48 } // Rationalnumber::simplify 53 49 54 55 // constructors 56 57 Rational rational() { 58 return (Rational){ 0, 1 }; 59 // Rational t = { 0, 1 }; 60 // return t; 50 Rational rational() { // constructor 51 // r = (Rational){ 0, 1 }; 52 Rational t = { 0, 1 }; 53 return t; 61 54 } // rational 62 55 63 Rational rational( long int n ) { 64 return(Rational){ n, 1 };65 //Rational t = { n, 1 };66 //return t;56 Rational rational( long int n ) { // constructor 57 // r = (Rational){ n, 1 }; 58 Rational t = { n, 1 }; 59 return t; 67 60 } // rational 68 61 69 Rational rational( long int n, long int d ) { 62 Rational rational( long int n, long int d ) { // constructor 70 63 long int t = simplify( &n, &d ); // simplify 71 64 // r = (Rational){ n / t, d / t }; … … 73 66 return t; 74 67 } // rational 75 76 77 // getter/setter for numerator/denominator78 68 79 69 long int numerator( Rational r ) { … … 89 79 } // numerator 90 80 91 long int denominator( Rational r ) {92 return r.denominator;93 } // denominator94 95 81 long int denominator( Rational r, long int d ) { 96 82 long int prev = r.denominator; … … 101 87 } // denominator 102 88 103 104 // comparison105 106 89 int ?==?( Rational l, Rational r ) { 107 90 return l.numerator * r.denominator == l.denominator * r.numerator; … … 127 110 return ! ( l < r ); 128 111 } // ?>=? 129 130 131 // arithmetic132 112 133 113 Rational -?( Rational r ) { … … 169 149 return t; 170 150 } // ?/? 171 172 173 // conversion174 151 175 152 double widen( Rational r ) { … … 211 188 } // narrow 212 189 213 214 // I/O215 216 190 forall( dtype istype | istream( istype ) ) 217 191 istype * ?|?( istype *is, Rational *r ) {
Note:
See TracChangeset
for help on using the changeset viewer.