Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Round to the nearest 0.33

    Hi

    I am trying to round all values with 2 decimal places to the nearest 0.33

    So for example if the number is 5.29 it would need to say 5.33. If the number is 5.54 then it should be rounded to 5.66, but if the number is 5.93 then it should be rounded to 6 (and not 5.99).


    The problem is that I cant figure out how to do that. If you have variable A and use round(A,1) it rounds to integer, if you use round(A,0.5) it rounds to nearest 0.5, but if you write round(A,0.33) you get some weird numbers.

    Does anyone have any ideas of how to do that?

    Cheers

    Aleksej

  • #2
    Code:
    clear
    input float x
    5.11
    6
    5.54
    5.93
    end
    
    g wanted= cond(round(mod(x, int(x)), 0.33) <=0.66, int(x)+ round(mod(x, int(x)), 0.33), int(x)+1)
    Res.:

    Code:
    . l
    
         +---------------+
         |    x   wanted |
         |---------------|
      1. | 5.11        5 |
      2. |    6        6 |
      3. | 5.54     5.66 |
      4. | 5.93        6 |
         +---------------+
    Last edited by Andrew Musau; 04 Nov 2022, 08:14.

    Comment


    • #3
      Strictly this is impossible except by multiplying by 3 and rounding to the nearest integer -- which is not what you want but a multiple of it.

      There are at least two levels of difficulty here:

      1. 1/3 and 2/3 do not have exact binary equivalents. The reason that rounding to the nearest half or integer works fine is that either kind of number does have an exact binary representation.

      2. Whatever you enter as a decimal 0.33, 0.333, 0.3333, ..., 0.66, 0.666, 0.6666, ..., or even 0.67, 0.667, 0.6667, ... is only an approximation to 1/3 or 2/3 respectively.

      Demonstration (I used Mata for my convenience, but Stata behaves the same way.)

      Code:
      . mata
      ------------------------------------------------- mata (type end to exit) ------------------------------------
      : round(3 * (5.29, 5.54, 5.93))
              1    2    3
          +----------------+
        1 |  16   17   18  |
          +----------------+
      
      : end
      --------------------------------------------------------------------------------------------------------------
      
      . di round(3 * 5.29)
      16
      If you said more about why you think you need this, there might be extra twists.

      The magic word is learn more is precision



      Code:
      search precision
      Last edited by Nick Cox; 04 Nov 2022, 08:33.

      Comment


      • #4
        Just to note more positively that feeding Stata with 1/3 or 2/3 rather than 0.33 or 0.66 or whatever obliges Stata to get as close as it can using binary representations.

        Comment

        Working...
        X