Announcement

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

  • Generated percent variable not rounding properly

    Hello,

    I generated a float variable of a percentage:


    g double share = weeks/tbw if fs==0
    replace share = round(share, 0.1)
    replace share = share*100

    Dataex input:

    clear
    input float(fs weeks) int tbw float fam_inc double share
    1 . 20 30295 .
    1 . 19 30295 .
    1 . 50 34752 .
    0 3 30 25528 10
    0 4 40 23408 10
    1 . 24 31911 .
    1 . 43 31798 .
    0 17 50 15625 30.000000000000004
    0 14 29 10581 50
    1 . 15 35026 .
    1 . 35 38734 .
    1 . 18 27337 .
    0 12 42 8673 30.000000000000004
    0 13 13 21922 100
    0 50 50 18412 100
    1 . 20 31228 .
    1 . 14 27775 .
    0 3 37 19436 10
    1 . 22 26442 .
    1 . 27 26661 .
    1 . 38 26661 .
    1 . 27 29479 .
    0 21 21 720 100
    1 . 73 31693 .
    0 39 50 13459 80
    1 . 27 34868 .
    1 . 23 34868 .
    0 9 9 1 100
    0 18 30 19989 60.00000000000001
    1 . 20 29150 .
    end
    [/CODE]

    I don't know why the 30% and 60%, is not rounded, but shows up as 60.0000000001.

    When I don't do a double, strange things are happening as well. It doesn't show up like that but I cant browse if I say "br if share==60".

    Thanks!

  • #2
    This is a precision problems, as I suppose you guessed wenn creating the variables explicitly as doubles. The problem is that 1/10 in binary is 0.111111111111111 etc. so it has to be rounded. The easiest sollution is first multiply by a 100 and than round to the closest multiple of 10, as 10 is a numer with a exact representation in binary (1010), so it does not have to be rounded.

    Code:
    gen double share = weeks/tbw if fs==0
    replace share = share*100
    replace share = round(share, 10)
    ---------------------------------
    Maarten L. Buis
    University of Konstanz
    Department of history and sociology
    box 40
    78457 Konstanz
    Germany
    http://www.maartenbuis.nl
    ---------------------------------

    Comment


    • #3
      Thank You

      Comment

      Working...
      X