44  lastLegal()

The examples in Chapter 44 require

library(groupedHyperframe)

Due to the floating-point precision of R (Listing 44.1), ratio of two double-precision scalars may take exceptional/illegal return of

Listing 44.1: Review: exceptional/illegal ratio due to floating-point precision (R Core Team 2025)
list(
  0 / c(2.6e-324, 2.5e-324),
  c(2.5e-324, 2.6e-324) / 0
)
# [[1]]
# [1]   0 NaN
# 
# [[2]]
# [1] NaN Inf

Function lastLegal() (Listing 44.5) returns the index of the last consecutive legal values in a double (Listing 44.2) vector, i.e., the first exceptional/illegal value of 0, Inf, or NaN appears at the next index. The term “legal” indicates

a double scalar being not-NA_real_, not-NaN, not-Inf (Listing 44.3), and with absolute value greater than .Machine$double.eps (Listing 44.4).

Listing 44.2: Advanced: NaN and Inf are double, not integer (R Core Team 2025)
list(Inf, NaN) |> 
  vapply(FUN = typeof, FUN.VALUE = '')
# [1] "double" "double"
Listing 44.3: Advanced: base::is.finite()
c(NA_real_, NaN, Inf) |>
  is.finite()
# [1] FALSE FALSE FALSE
Listing 44.5: Example: function lastLegal(), toy examples
list(
  toy1 = c(exp(1), pi),
  toy2 = c(exp(1), pi, NaN),
  toy3 = c(exp(1), pi, NaN, 1, 0, Inf)
) |> 
  lapply(FUN = lastLegal)
# $toy1
# [1] 2
# attr(,"value")
# [1] 3.141593
# 
# $toy2
# [1] 2
# attr(,"value")
# [1] 3.141593
# 
# $toy3
# [1] 2
# attr(,"value")
# [1] 3.141593