• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Crazy floats
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Crazy floats


  • Subject: Re: Crazy floats
  • From: Ricky Sharp <email@hidden>
  • Date: Fri, 23 Jul 2004 08:39:49 -0500

On Friday, July 23, 2004, at 08:32AM, Lorenzo <email@hidden> wrote:

>I have a floats with 3 values but if I add many times the value 0.2 to one
>item, it gets some decimal value more. Instead of -0.693000, I get
>-0.693001. Why do I get the 1 at the end?
>
> float positions[3];
>
> positions[0] = -0.693000; // currentPoint
> positions[1] = positions[0] + 2; // endPoint
> positions[2] = increment = 0.2; // increment
>
>so I try to add the increment to the "currentPoint" value until it is equal
>to the "end" value.
>
> while(positions[0] != positions[1]){
> positions[0] += positions[2];
> NSLog(@"currentPoint %f, end %f, increm %f",
> positions[0], positions[1], positions[2]);
> }
>
>And since they are never equal, this produces an "infinite loop" (I am not
>speaking about the Apple address).

This is why a course in "numerical analysis" is very important :) Not all real-world values can be represented by floating point values.

This is not unique to Cocoa, or specifically to the float type, but to any floating point value. You should _never_ perform exact comparissons. Instead, use either an integral loop variant (e.g int, long), or use >, >=, <, or <= comparissons.

Rick Sharp
Instant Interactive(tm)
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.


  • Prev by Date: Re: Memory management, when mixing C and ObjC
  • Next by Date: Re: Re: Memory management, when mixing C and Obj C
  • Previous by thread: Crazy floats
  • Next by thread: Re: Crazy floats
  • Index(es):
    • Date
    • Thread