What am I doing wrong here - canFind with iota is not working

John Colvin via Digitalmars-d digitalmars-d at puremagic.com
Thu Feb 26 04:32:47 PST 2015


On Thursday, 26 February 2015 at 11:00:05 UTC, John Colvin wrote:
> On Thursday, 26 February 2015 at 10:55:43 UTC, Kingsley wrote:
>> float oneDegree = (PI / 180.0);
>> float first = -(oneDegree * 10.0);
>> float second = (oneDegree * 10.0);
>> float step = 0.000001;
>> float[] r = iota(first,second,step).array;
>>
>> writeln(r);
>>
>> float item = 0.174531;
>> writeln(r.canFind(item));
>>
>>
>> // returns false for canFind - even though that float is in 
>> the array ???
>
> Never check floating point numbers for equality, unless you've 
> really thought about how the floating point arithmetic for this 
> specific problem will go. Pretty much the only place it's 
> useful to do is in unit tests for maths libraries.

This is the classic reference on the topic: 
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

but there are loads of other less rigorous explanations around 
the web.

To cut a long story short: floating point maths is not the same 
as maths with real numbers. It's mostly roughly the same, 
sometimes catastrophically different and very, very rarely 
exactly the same.


More information about the Digitalmars-d mailing list