Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #5639

Re: Converting Floats to Strings yields erratic results

From "Dirk T. Shelley" <nospam@nospam.com>
Newsgroups comp.lang.c
Subject Re: Converting Floats to Strings yields erratic results
Date 2011-06-08 16:34 +0000
Organization Aioe.org NNTP Server
Message-ID <iso8aa$9ng$1@speranza.aioe.org> (permalink)
References <ism43f$cg1$1@speranza.aioe.org> <lnpqmpe3lu.fsf@nuthaus.mib.org>

Show all headers | View raw


Keith Thompson writes:

> "Dirk T. Shelley" <nospam@nospam.com> writes:
>>    I'm writing, for my own personal enlightenment, a little program
>> that will convert a floating-point number, passed as an argument on the
>> command line, into a character string.  I'm now aware of sprintf(), but
>> I wasn't when I started writing this program, and I feel it is my duty
>> to finish it ;-)
> 
> Typically you *can't* pass floating-point numbers on the command line.
> You can only pass strings.  Presumably you convert those strings to
> floating-point numbers somehow, but you don't tell us how.
> 
>>    Everything, in general, works fine, except that some values are
>> converted to one less than their actual value.  For example, 15 returns
>> 15, 14.123 returns 14, but 14 returns 13.  I am _completely_ clueless,
>> although I suspect it has something to do with rounding and truncating
>> happening behind my back.  The important part is as follows...
> 
> If you don't underrstand what's happening, how do you know that this is
> the important part?
> 
>>  while (foo >= 10) {
>>         foo = foo/10.0;
> 
> This will yield an inexact result (and for all we know the original
> value of foo was inexact).  Floating-point numbers are represented in
> binary, not decimal.
> 
> Suggested reading: section 14 of the comp.lang.c FAQ,
> <http://www.c-faq.com/>.  For more advanced reading, search for
> Goldberg's "What Every Computer Scientist Should Know About
> Floating-Point Arithmetic".
> 
>>         tenDivs++;
>>     }
>>
>>     i = 0;
>>     while (tenDivs >= 0) {
>>         while (!(foo < 1)) {
>>                 foo--;
>>                 oneDivs++;
>>         }
>>         str[i] = 48 + oneDivs;
> 
> Where did the value 48 come from?
> 
> Oh, I see, it's the ASCII value of '0'.  Just write '0' (yes, character
> constants are of type int); it makes your code clearer and potentially
> more portable.  It assumes that the representations of '0' through '9'
> are contiguous; as it happens, the language guarantees that.
> 
>>         foo = foo * 10;
>>         oneDivs = 0;
>>         tenDivs--;
>>         i++;
>>     }
>>
>> Where "foo" is the value to be converted.  Can anybody help, or point
>> me to a source that can?
> 
> I haven't taken the time to analyze what your program is doing, but
> consider this.  As I mentioned above, dividing a floating-point number x
> by 10.0 is likely to give you an inexact result. Multiplying that result
> by 10.0 could give you something other than the original number, and
> truncating that result could give you x - 1.
> 
>> In an unrelated question: Does anyone know of any link which describes
>> the (relative) performance of all kinds of C operations? e.g: how fast
>> is "add" comparing with "multiplication" on a typical  machine.
> 
> I don't know.  You can probably assume that addition is faster than
> multiplication, and division is slower than either, but there are no
> consistent guarantees.  The relative performance of integer and
> floating-point arithmetic can vary a great deal depending on the
> hardware.

Thanks for all the responses.

I think I now have a vague understanding of the nature of the
problem, though not enough to fix it.  My complete code is as follows
if anyone cares to further pick it apart.

#include<stdio.h>
#include<stdlib.h>

int main(int argc, char *argv[]) {
    int tenDivs, oneDivs, i, neg_foo;
    char str[sizeof(float)+1];
    float foo;

    /* Make sure the user entered a number, and retrieve it's value.
*/
    switch (argc) {
        case 1:
                printf("Not enough arguments.\n");
                exit(0);
                break;
        case 2:
                foo = atof(argv[1]);
                break;
        default:
                printf("Too many arguments.\n");
                exit(0);
                break;
    }

    tenDivs = 0;
    oneDivs = 0;
    neg_foo = 0;

    /* if foo is a negative number, make it positive and take note */
    if (foo < 0) {
        foo = 0 - foo;
        neg_foo = 1;
    }

    while (foo >= 10) {
        foo = foo/10.0;
        tenDivs++;
    }

    i = 0;
    while (tenDivs >= 0) {
        while (foo >= 1) {
                foo--;
                oneDivs++;
        }
        str[i] = 48 + oneDivs;
        foo = foo * 10;
        oneDivs = 0;
        tenDivs--;
        i++;
    }

    str[i] = '\0';

    /* if foo was positive, we are done. */
    if (neg_foo == 0)
        printf("The value of str is: %s\n", str);

    /* if foo was negative, adjust our value. */
    if (neg_foo == 1) {
        while (i >= 0) {
                str[i+1] = str[i];
                i--;
        }
        str[0] = '-';
        printf("The value of str is: %s\n", str);
    }

    return 0;
}

Back to comp.lang.c | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Converting Floats to Strings yields erratic results "Dirk T. Shelley" <nospam@nospam.com> - 2011-06-07 21:10 +0000
  Re: Converting Floats to Strings yields erratic results Keith Thompson <kst-u@mib.org> - 2011-06-07 14:25 -0700
    Re: Converting Floats to Strings yields erratic results Peter Nilsson <airia@acay.com.au> - 2011-06-07 20:13 -0700
      Re: Converting Floats to Strings yields erratic results Keith Thompson <kst-u@mib.org> - 2011-06-07 20:27 -0700
    Re: Converting Floats to Strings yields erratic results "Dirk T. Shelley" <nospam@nospam.com> - 2011-06-08 16:34 +0000
      Re: Converting Floats to Strings yields erratic results Ian Collins <ian-news@hotmail.com> - 2011-06-09 07:53 +1200
        Re: Converting Floats to Strings yields erratic results "Dirk T. Shelley" <nospam@nospam.com> - 2011-06-08 20:46 +0000
      Re: Converting Floats to Strings yields erratic results "BartC" <bc@freeuk.com> - 2011-06-08 22:40 +0100
        Re: Converting Floats to Strings yields erratic results "BartC" <bc@freeuk.com> - 2011-06-09 11:03 +0100
          Re: Converting Floats to Strings yields erratic results James Kuyper <jameskuyper@verizon.net> - 2011-06-09 08:06 -0400
            Re: Converting Floats to Strings yields erratic results "BartC" <bc@freeuk.com> - 2011-06-09 16:57 +0100
          Re: Converting Floats to Strings yields erratic results Noob <root@127.0.0.1> - 2011-06-09 14:13 +0200
          Re: Converting Floats to Strings yields erratic results Keith Thompson <kst-u@mib.org> - 2011-06-09 09:26 -0700
            Re: Converting Floats to Strings yields erratic results "BartC" <bc@freeuk.com> - 2011-06-09 19:07 +0100
              Re: Converting Floats to Strings yields erratic results Keith Thompson <kst-u@mib.org> - 2011-06-09 11:52 -0700
                Re: Converting Floats to Strings yields erratic results "BartC" <bc@freeuk.com> - 2011-06-09 20:30 +0100
            Re: Converting Floats to Strings yields erratic results "io_x" <a@b.c.invalid> - 2011-06-13 12:21 +0200
            Re: Converting Floats to Strings yields erratic results "io_x" <a@b.c.invalid> - 2011-06-13 22:31 +0200
          Re: Converting Floats to Strings yields erratic results Noob <root@127.0.0.1> - 2011-06-10 10:58 +0200
            Re: Converting Floats to Strings yields erratic results Seebs <usenet-nospam@seebs.net> - 2011-06-10 22:49 +0000
      Re: Converting Floats to Strings yields erratic results Eric Sosman <esosman@ieee-dot-org.invalid> - 2011-06-08 21:51 -0400
      Re: Converting Floats to Strings yields erratic results Mark Bluemel <mark_bluemel@pobox.com> - 2011-06-09 08:50 +0100
  Re: Converting Floats to Strings yields erratic results gordonb.9ycz5@burditt.org (Gordon Burditt) - 2011-06-07 18:13 -0500
  Re: Converting Floats to Strings yields erratic results Eric Sosman <esosman@ieee-dot-org.invalid> - 2011-06-07 20:47 -0400
    Re: Converting Floats to Strings yields erratic results Keith Thompson <kst-u@mib.org> - 2011-06-07 20:08 -0700
      Re: Converting Floats to Strings yields erratic results Eric Sosman <esosman@ieee-dot-org.invalid> - 2011-06-07 23:38 -0400
    Re: Converting Floats to Strings yields erratic results Eric Sosman <esosman@ieee-dot-org.invalid> - 2011-06-07 23:49 -0400
      Re: Converting Floats to Strings yields erratic results Shao Miller <sha0.miller@gmail.com> - 2011-06-08 00:54 -0500
  Re: Converting Floats to Strings yields erratic results Thad Smith <ThadSmith@acm.org> - 2011-06-07 20:38 -0700
    Re: Converting Floats to Strings yields erratic results Keith Thompson <kst-u@mib.org> - 2011-06-07 20:30 -0700
  Re: Converting Floats to Strings yields erratic results falk@rahul.net (Edward A. Falk) - 2011-06-08 20:54 +0000
    Re: Converting Floats to Strings yields erratic results Eric Sosman <esosman@ieee-dot-org.invalid> - 2011-06-08 21:56 -0400

csiph-web