Announcement

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

  • loss of precision from mata to stata

    Dear all,

    I am trying to do something very simple. I just want to get the max of a set of numbers stored in a local macro `vcnumbers`. I converted this set of numbers into a matrix in Mata, got the max, and then sent it back to Stata in a local macro `maxvc`. As you can see in the replicable example below, the number obtained in Mata (20191018165607) is different from the one sent to Stata (20200000000000). Do you know how can I get the right number back in Stata? I guess I am doing something wrong by converting to reals and then to strings again but, up to my knowledge, there is no other way to export local macros in Stata from Mata, is that right?

    Code:
    local vcnumbers `" "20190812180416" "20190819173838" "20191008105614" "20191008140743" "20191008141755"  "20191018165607" "'
    
    mata {
         VC = strtoreal(tokens(`"`vcnumbers'"'))
         printf("%15.0f\n" , max(VC))
         st_local("maxvc", strofreal(max(VC)))
    }
    
    disp %15.0f `maxvc'


    Thank you so much!

    PS: In case you're wondering why the local macro `vcnumbers` is stored in that way, it is because it comes from

    Code:
    local vcnumbers: dir "." files "zzz*"
    local vcnumbers: subinstr     local vcnumbers "zzz" "", all
    best,
    Best,
    Pablo Bonilla

  • #2
    You need to specify a format as the second argument to strofreal(), since the default behavior does not give you full precision.
    Code:
    . local vcnumbers `" "20190812180416" "20190819173838" "20191008105614" "20191008140743" "201910
    > 08141755"  "20191018165607" "'
    
    .
    . mata {
    >      VC = strtoreal(tokens(`"`vcnumbers'"'))
    >      printf("%15.0f\n" , max(VC))
    >      st_local("maxvc1", strofreal(max(VC)))
    >      st_local("maxvc2", strofreal(max(VC),"%15.0f"))
    > }
     20191018165607
    
    .
    . macro list _maxvc1 _maxvc2
    _maxvc1:        2.02e+13
    _maxvc2:        20191018165607

    Comment


    • #3
      Ah, This is awesome!

      Thank you so much, Willliam. Highly appreciated.

      Best,
      Pablo
      Best,
      Pablo Bonilla

      Comment

      Working...
      X