Skip to content

Instantly share code, notes, and snippets.

@LogIN-
Created August 17, 2017 23:49
Show Gist options
  • Save LogIN-/ce290cc1e4595986d41f201fe6ecbf6d to your computer and use it in GitHub Desktop.
Save LogIN-/ce290cc1e4595986d41f201fe6ecbf6d to your computer and use it in GitHub Desktop.
Extract Mantissa and Exponent of the Floating-Point Value
#!/usr/bin/Rscript --vanilla
#
# Author: LogIN- <info{@/at}ivantomic{.}com
# License: MIT
#
# Description:
#
# Extract Mantissa and Exponent of the Floating-Point Value
# frexp() returns an list containing Mantissa and Exponent of the Floating-Point Value
#
# Parameters:
# arg
# number
#
# Example:
# frexp(1.5)
# => [0.75, 1]
frexp <- function(input){
input <- as.numeric(input)
result <- c(0, 0)
if (input != 0 && is.finite(input)) {
absInp <- abs(input)
exp <- max(-1023, floor(log2(absInp)) + 1)
x <- absInp * 2^ -exp
while (x < 0.5) {
x <- x * 2
exp <- exp - 1
}
while (x >= 1) {
x <- x * 0.5
exp <- exp + 1
}
if (input < 0) {
x <- -x
}
result <- c(x, exp)
}
return(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment