vendredi 31 mai 2019

Unexpected "{" when many if's and if-else structures are mixed together?

When trying to write a function fromNdpTo10 that converts normalized double precision number (in memory) to decimal number, I get "unexpected '{' in:" error, but I should not get that error. I cared the opening and closing number of paranthesis, braces, brackets to be equal. Look:

SubstringHoldingLeading0s <- function(x) { 
  x <- formatC(x, flag="0", width=11, format="d") 
  substr(x, 1, 11) 
}
SubstringHoldingLeading0s(00100101101) # "00100101101"

from2to10 <- function(binaryNumber) {
  # Via SubstringHoldingLeading0s, the loss is prevented when converting string (holded as numeric) to character
  sapply(strsplit(SubstringHoldingLeading0s(binaryNumber), split = ""), function(x) sum(as.numeric(x) * 2^(rev(seq_along(x) - 1))))}
from2to10(00100101101) # 301

fromNdpTo10 <- function(NdpNumber) {
  NdpNumber <- as.character(NdpNumber)
  out <- list()

  # Handle special cases (0, Inf, -Inf)
  if (NdpNumber %in% c(
    "0000000000000000000000000000000000000000000000000000000000000000",
    "0111111111110000000000000000000000000000000000000000000000000000",
    "1111111111110000000000000000000000000000000000000000000000000000")) {
    # special cases
    if (NdpNumber == "0000000000000000000000000000000000000000000000000000000000000000") { out <- "0" }
    if (NdpNumber == "0111111111110000000000000000000000000000000000000000000000000000") { out <- "Inf" }
    if (NdpNumber == "1111111111110000000000000000000000000000000000000000000000000000") { out <- "-Inf" }
  } else { # if NdpNumber not in special cases, begins

    signOfNumber <- "+" # initialization
    If (substr(NdpNumber, 1, 1) == 0) { signOfNumber <- "+"
    } else { signOfNumber <- "-" }

    # From BiasedExponent to RealExponent (Biased Exponent=Real exponent +1023;  Real exponent=Biased Exponent-1023)
    BiasedExponent <- substr(NdpNumber, 2, 12)
    BiasedExponent <- from2to10(BiasedExponent)
    RealExponent <- BiasedExponent - 1023


    # Significand
    Significand <- substr(NdpNumber, 13, 64)
    Significand <- from2to10(Significand)

    out <- paste0(c(signOfNumber, Significand, "e", RealExponent), collapse = '')
  } # if NdpNumber not in special cases, ends

  out
}

The (unexpected for me) error is:

Error: unexpected '{' in:
"        signOfNumber <- "+" # initialization
        If (substr(NdpNumber, 1, 1) == 0) {"

The problem seems to be caused by many if's and if-else structures are mixed together. Any idea on how to solve the problem?

Aucun commentaire:

Enregistrer un commentaire