Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Special Interest Groups
  3. C++ Gurus
  4. [SOLVED] double precision in for-loops
QtWS25 Last Chance

[SOLVED] double precision in for-loops

Scheduled Pinned Locked Moved C++ Gurus
3 Posts 2 Posters 2.0k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • D Offline
    D Offline
    david.luggen
    wrote on last edited by
    #1

    Hey there

    I have a short question about doubles in for-loops.

    @
    for(double i=0.0; i<=2.0; i+=0.1)
    @

    In the above example it ignores the last step 2.0, so what I get is i until 1.9. If I'm doing this

    @
    for(double i=0.0; i<=2.0000001; i+=0.1)
    @

    The last step 2.0 is also executed. Does somebody know a better solution to this problem instead of my hack there?

    1 Reply Last reply
    0
    • A Offline
      A Offline
      andre
      wrote on last edited by
      #2

      You could use qFuzzyCompare instead of the =, but that would mean rewriting your loop to:

      @
      for(double d=0.0; d<2.0 || qFuzzyCompare(d, 2.0); d+=0.1)
      @

      Or, you get rid of using floating points in your loop completely, and do:
      @
      for(int i=0; i<=20; i+=1) {
      double d = double(i) / 10.0; //use d for whatever you wanted done
      @

      The root problem is that because floating points are never precise, comparisons with floating points are not precise either.

      1 Reply Last reply
      0
      • D Offline
        D Offline
        david.luggen
        wrote on last edited by
        #3

        Hmm, even qFuzzyCompare does not work. Well there is only the int conversion way. Thx anyway!

        Edit: My fault, qFuzzyCompare works, but as you said, comparing doubles can't be the way.

        1 Reply Last reply
        0

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved