Why do powers of 10 print in scientific notation at the 5th power?

前端 未结 2 1106
广开言路
广开言路 2021-02-02 06:38

I would like to know if and how the powers of 10 are related to the printing of scientific notation in the console. I\'ve searched R docs and haven\'t found anything relevant,

2条回答
  •  一向
    一向 (楼主)
    2021-02-02 07:32

    I'm confused as to what exactly is your question; or, more specially, how you would use an answer to this question to somehow change/control the behavior of R. You you trying to format numbers a certain way? There are better ways to do that.

    When you type values like that, the results are implicitly run though one of the print() commands to be formatted "nicely" to the console. Whenever things have to look "nice" on screen, the code to do that is often ugly. Here most of the that code is taken care of by the formatReal function, and the helper scientific function. The latter tracks the following information for a number

    /* for a number x , determine
     *  sgn    = 1_{x < 0}  {0/1}
     *  kpower = Exponent of 10;
     *  nsig   = min(R_print.digits, #{significant digits of alpha})
     *  roundingwidens = 1 if rounding causes x to increase in width, 0 otherwise
     *
     * where  |x| = alpha * 10^kpower   and  1 <= alpha < 10
     */
    

    Then the former function uses this information to try to make "nice" looking numbers by balancing values to the left and the right of the decimal place. It's a combination of many things like the order of magnitude of the number and the number of significant digits as well as environmental influences form the scipen option, etc.

    print() is only meant to make things look "nice." What exactly is nice depends on all the values in a vector. You'll find few hard cutoffs in that code; it's very adaptive. There is no easy way to concisely describe everything it does in the general case (which is what it sounds like you are asking for).

    The only thing that is certain is that if you need to have your numbers formatted in a certain way, use a function like sprintf() or formatC() that allows for precise control.

    Of course this behavior is dependent on class() and i've pointed the the formatReal stuff since that's where most tricky things happen. But observe the difference when you use integers

    c(10, 100, 1000, 10000, 100000)
    # [1] 1e+01 1e+02 1e+03 1e+04 1e+05
    c(10L, 100L, 1000L, 10000L, 100000L)
    # [1]     10    100   1000  10000 100000
    

提交回复
热议问题