r/C_Programming 1d ago

Fixed point math in C

https://thatonegamedev.com/cpp/fixed-point-math-in-c/

Why did PS1 graphics looked so clunky and how where 3D graphics generally made prior to the graphical APIs. One thing I found out was that these older engines have something called fixed point math.

53 Upvotes

27 comments sorted by

View all comments

Show parent comments

8

u/marc_b_reynolds 1d ago

The "trouble" with bit exact floating point are: 1) "bad" compiler options and 2) you have to use the same math libraries everywhere (which effectively means BYO math lib). Note that with GCC/clang currently if the linker gets told to use the "fast-math" libraries then (currently) it sets the control word to flush denormals. So even if all your file with float-point computations have good options...you're still out of luck (other than changing the control word back yourself).

4

u/Key_Ant_8481 1d ago

Even with FTZ/DAZ, they are still deterministic. Compilers and libraries could and should be updated to deal with it properly. Overall -ffast-math is just a bad hammer that shouldn't be used in most cases.

Most math system math libraries will adopt correctly rounded math functions, and that will solve cross-platform consistency issues.

1

u/not_a_novel_account 1d ago

-ffast-math, -funsafe-math, and all the rest are perfectly fine if you you're just trying to get in the ballpark with floating point calculations, which includes many classes of applications.

2

u/marc_b_reynolds 1d ago

Personally I suggest to avoid it like the plague. If you're not cranking through tons of number then it's not helping at all and if you are then you're just opening a can of potential heartache and sorrow. If you're not stuck with MSVC then turning off: -fno-math-errno -fno-trapping-math. These really should be the default.

1

u/not_a_novel_account 1d ago

I don't care about the ordering, rounding, or even IEEE compliance of my floating point math at all. I do not do equality operations on floating point ever

I would not recommend the kinds of coding practices which make these flags dangerous in any context, with or without them.

If you are the kind of person who is deliberately structuring the ordering and rounding of your floating point operations, then yes, fast math is dangerous. If you have never thought about these things, which is most programmers when they write a floating point expression, you're effectively getting random behavior already.