rational-class: Rational Number Classes

rational-classR Documentation

Rational Number Classes

Description

An S3, S4, and R6 class for a rational number

  • rationalS3 - access fields with the '$' operator.

  • rationalS4 - access fields with the '@' operator.

  • rationalR6 - internal elements are private, so fields are accessed with accessor methods, $getNumerator(), $getDenominator(), $getValue()

The classes are designed to be used in a similar way to integers and numerics in R.

generator rational number of class rationalS3, rationalS4, and rationalR6. Each type of class has advantages and disadvantages in performance and flexibility

Usage

rational(n, d, method = "R6")

Arguments

n

the numerator

d

the denominator

method

a length = 1 character vector. One of "R6" (default), "S3", "S4"

Value

the desired instance of the rational class

Fields

n,d,v

the numerator, denominator, and value field of the S3 class

Slots

n

the numerator of the S4 class

d

the denominator of the S4 class

v

the numeric value of the S4 class

Note

note that Inf, NA, NaN, and NULL all fail on is.integer() and are not permitted

Examples

 a <- rational(1L, 3L, method="S3")
 stopifnot(a$n == 1L && a$d == 3L && abs(a$v - 1/3) < 1E-12)
 stopifnot(class(a) == "rationalS3")

 b <- rational(2L, 5L, method="S4")
 stopifnot(b@n == 2L && b@d == 5L && abs(b@v - 2/5) < 1E-12)
 stopifnot(class(b) == "rationalS4" && isS4(b) && is(b, "rationalS4"))

 d <- rational(3L, 7L, method="R6")
 stopifnot(d$getNumerator() == 3L && d$getDenominator() == 7L)
 stopifnot(abs(d$getValue() - 3/7) < 1E-12)
 stopifnot(class(d)[1] == "rationalR6" && is(d, "rationalR6") && is(d, "R6"))

 e <- rational(3L, 7L, method="S7")
 stopifnot(e@n == 3L && e@d == 7L && abs(e@v - 3/7) < 1E-12)
 stopifnot(class(e)[1] == "rational::rationalS7")
 stopifnot(is(e, "rational::rationalS7") && is(e, "S7_object"))

bertcarnell/rational documentation built on Aug. 1, 2024, 8:14 p.m.