Loading ...
Sorry, an error occurred while loading the content.

Re: floating problem of eval()

Expand Messages
  • Vlad Irnov
    ... 0 ... 0.5 ... 0 ... 0 The workaround I use is to have the code that does calculations in a separate Python module which imports division from future, and
    Message 1 of 6 , Nov 13, 2012
    • 0 Attachment
      On Tuesday, November 13, 2012 1:46:00 AM UTC-5, JohnBeckett wrote:
      > oversky wrote:
      >
      > > :echo eval('1/2')
      >
      > > 0
      >
      >
      >
      > As Danny mentioned, that is not strange as Vim follows the same
      >
      > concepts as used in the C language (and others) where "1" is an
      >
      > integer, but "1.0" (both without quotes) is a floating point
      >
      > number.
      >
      >
      >
      > You get the same in Python 2.7, where 1/2 also evaluates as 0.
      >
      >
      >
      > You don't need "eval":
      >
      > :echo 1.0/2
      >
      > gives
      >
      > 0.5
      >
      >
      >
      > If you have numbers as strings in variables, you could convert
      >
      > them to floats like this:
      >
      > :let n = "1"
      >
      > :let d = "2"
      >
      > :echo str2float(n)/str2float(d)
      >
      > which gives 0.5.
      >
      >
      >
      > John


      In Python 2.x this is easily solved like this:
      >>> 1/2
      0
      >>> from __future__ import division
      >>> 1/2
      0.5

      Unfortunately, my Vim is not able to import from future:
      :py print 1/2
      0
      :py from __future__ import division
      :py print 1/2
      0

      The workaround I use is to have the code that does calculations in a separate Python module which imports division from future, and then import that module from Vim script. I can post my script for inline calculations with Pythons if someone is interested.

      There other advantages in using Python for calculations instead of VimScript.
      Integer overflow is less likely to be a problem. This is what I get:
      :echo 111111111*111111111
      165372529
      :py print 111111111*111111111
      12345678987654321

      The x**y notation is more convenient than pow(x,y).

      Regards,
      Vlad

      --
      You received this message from the "vim_use" maillist.
      Do not top-post! Type your reply below the text you are replying to.
      For more information, visit http://www.vim.org/maillist.php
    Your message has been successfully submitted and would be delivered to recipients shortly.