# Floating Point Accuracy

This topic is 2346 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Ok, so in some places in my code I have things like this:

(where SCUBE_SIZE = 1.5f and SECTOR_BSIZE = 128)
[code]
for (uint32 y = 0; y < uint32(depth_ / SCUBE_SIZE) / SECTOR_BSIZE; ++y)
[/code]

These SHOULD always come out as whole numbers... But am I setting myself up for trouble?? (It seems like I am)

==EDIT==
I guess I'm asking, if I multiply A (a float, representing a whole number) by B (a float) and then devide A by B, am I going to get my original number back always?
(This is assuming B has few significant digits, like 3 or less)

==EDIT2==
It HAS worked so far... But I sure don't like the looks of it.

##### Share on other sites
This is a remarkably unreliable thing to do.

Instead, if you can afford the risk of overflow, multiply by 3 and divide by 2. Then all your arithmetic is integers and safely accurate.

##### Share on other sites
Or rather the other way around in this case

All the code really needs to do is to divide by 192, which you could write like this:[code]const uint32 Divisor = (SECTOR_BSIZE + SECTOR_BSIZE / 2);

for (uint32 y = 0; y < depth_ / Divisor; ++y):[/code]Note that I very much don't care for the trailing underscores

##### Share on other sites
Yeah, I'm not really surprised this is a bad idea.

As for the trailing underscores, I picked that up a while back as a succinct way to differinciate private variables while still preserving readability.

e.g.
[code]
{
public:

VertexFormat GetFormat ();
IDirect3DVertexDeclaration9* GetDeclaration ();

private:
VertexFormat format_;
IDirect3DVertexDeclaration9* declaration_;
};
[/code]

I like it better than m_variableName but if there is something fundamentally bad here I will rethink things.

EDIT: I wish whitespace wasn't so broken in 'code'

##### Share on other sites
[quote name='jamesleighe' timestamp='1310743597' post='4835685']As for the trailing underscores, I picked that up a while back as a succinct way to differinciate private variables while still preserving readability.
I like it better than m_variableName but if there is something fundamentally bad here I will rethink things.
[/quote]
There's no problem with using trailing underscores.

##### Share on other sites
[quote]I guess I'm asking, if I multiply A (a float, representing a whole number) by B (a float) and then devide A by B, am I going to get my original number back always?[/quote]

As long as A, B, and A*B are all representable exactly, then (A * B) / A = B

I'm not sure why you're using floats when you're intending to store integers inside them. FYI casting from a float to an integer is a relatively expensive operation.

##### Share on other sites

This topic is 2346 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.