Skip to content

Commit 838ccb3

Browse files
committed
Rational utilities
1 parent 2fed160 commit 838ccb3

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

Runtime/Numerics/Rational.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,22 @@ public Rational Pow( int pow ) =>
8080
public static Rational Lerp( Rational a, Rational b, Rational t ) => a + t * ( b - a );
8181
public static Rational InverseLerp( Rational a, Rational b, Rational v ) => ( v - a ) / ( b - a );
8282

83+
public static Rational Floor( Rational r ) {
84+
if( r.n < 0 )
85+
return ( r.n - r.d + 1 ) / r.d;
86+
return r.n / r.d;
87+
}
88+
89+
public static Rational Ceil( Rational r ) {
90+
if( r.n > 0 )
91+
return ( r.n + r.d - 1 ) / r.d;
92+
return r.n / r.d;
93+
}
94+
95+
public static Rational Round( Rational r ) {
96+
return r.n < 0 == r.d < 0 ? ( r.n + r.d / 2 ) / r.d : ( r.n - r.d / 2 ) / r.d;
97+
}
98+
8399
// type casting
84100
public static implicit operator Rational( int n ) => new(n, 1);
85101
public static explicit operator int( Rational r ) => r.IsInteger ? r.n : throw new ArithmeticException( $"Rational value {r} can't be cast to an integer" );

0 commit comments

Comments
 (0)