Why does the number 1e9999… (31 9s) cause problems in R?

前端 未结 3 1527
执笔经年
执笔经年 2021-02-05 01:16

When entering 1e9999999999999999999999999999999 into R, R hangs and will not respond - requiring it to be terminated.

It seems to happen across 3 different

3条回答
  •  执笔经年
    2021-02-05 01:49

    This looks like an extreme case in the parser. The XeY format is described in Section 10.3.1: Literal Constants of the R Language Definition and points to ?NumericConstants for "up-to-date information on the currently accepted formats".

    The problem seems to be how the parser handles the exponent. The numeric constant is handled by NumericValue (line 4361 of main/gram.c), which calls mkFloat (line 4124 of main/gram.c), which calls R_atof (line 1584 of main/util.c), which calls R_strtod4 (line 1461 of main/util.c). (All as of revision 60052.)

    Line 1464 of main/utils.c shows expn declared as int and it will overflow at line 1551 if the exponent is too large. The signed integer overflow causes undefined behavior.

    For example, the code below produces values for exponents < 308 or so and Inf for exponents > 308.

    const <- paste0("1e",2^(1:31)-2)
    for(n in const) print(eval(parse(text=n)))
    

    You can see the undefined behavior for exponents > 2^31 (R hangs for an exponent = 2^31):

    const <- paste0("1e",2^(31:61)+1)
    for(n in const) print(eval(parse(text=n)))
    

    I doubt this will get any attention from R-core because R can only store numeric values between about 2e-308 to 2e+308 (see ?double) and this number is way beyond that.

提交回复
热议问题