Image

Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Compile-time rounding with the pre-processor

+8
−0

When searching the Internet, I came across this SO post Rounding in C Preprocessor but immediately noted that none of the answers are showing a way to perform actual rounding - rather, they are doing flooring to the nearest integer.

The post is actually misleading and got nothing to do with rounding, but with getting the appropriate integer type back from the macro. Yet it is the #1 search engine hit when searching for rounding the the preprocessor, which is kind of sad.

Is there a way to round a floating point expression to an integer at compile-time, using the pre-processor?

I suppose such code could also either be written in a type-generic way accepting any of the common arithmetic types as input, or alternatively in a type safe manner only accepting one specific type as input. Is there an advantage in using one form or the other?

History

0 comment threads

3 answers

+6
−0

It doesn't really need to be carried out in the preprocessor as such, it is sufficient to realize that a constant expression in C, consisting only of constants ("literals") is always calculated at compile-time.

The actual math for doing rounding is then rather trivial. Example:

float some_float = 3.14f;
uint32_t result = some_float - (uint32_t)some_float > 0.5f ? 
                  (uint32_t) some_float+1 :
                  (uint32_t) some_float;

The compiler with optimizations enabled will just replace that with 3 at compile-time.

Turning that same code into a macro:

#define ROUND(flt)   ( (flt)-(uint32_t)flt > 0.5f ?     \
                       (uint32_t)flt+1 :                \
                       (uint32_t)flt )  

As long as flt is a constant expression, this will all get calculated at compile-time.


Regarding type safety:

The above macro would be type-generic, as in the macro will accept any arithmetic expression containing, float, double, int etc and return a uint32_t. The advantage/disadvantage is that a lot of constant expressions might not always have an obvious type due to implicit type promotion. For example something like true ? 1 : 0.0 always returns 1.0 and in a type that is double.

If we want to allow that or not depends on how stringent we are with types. In some hardware-restricted applications like microcontroller ones, there may not be a FPU present at all (very common) or there might be a FPU but only single-precision (Cortex M3 etc). In some cases, a target-aware IDE might decide to link in a big software floating-point lib just because it spotted the presence of a floating point type not supported by hardware, and that's generally a bad thing. Especially if we only wanted to do floating point as part of the preprocessor and keep all run-time calculations in fixed point, because we are using some low- to mid-range MCU.

Casting the expression back to an integer type may or may not mean that the IDE will not link in that software floating point lib. To avoid such situations in certain IDEs, then a type safe macro makes sense, to prevent that from happening by accident.

By taking some of the tricks from How to create meaningful error messages from _Generic macros?, such a type safe macro with meaningful compiler errors might look like this:

#define STATIC_ASSERT_EXPR(expr, msg) ( (void)(struct{ int dummy; static_assert(expr, msg); }){}.dummy )
#define IS_FLOAT(expr) _Generic((expr), float: true, default: false)

#define ROUNDF(flt) ( STATIC_ASSERT_EXPR(IS_FLOAT(flt), "Wrong argument " #flt " passed to ROUNDF, expected float.") \
                      , /* comma operator */           \
                      ((flt)-(uint32_t)flt > 0.5f ?    \
                      (uint32_t)flt+1 :                \
                      (uint32_t)flt )                  \
                    )

Complete example:

#include <stdint.h>
#include <stdio.h>
#include <inttypes.h>

#define STATIC_ASSERT_EXPR(expr, msg) ( (void)(struct{ int dummy; static_assert(expr, msg); }){}.dummy )
#define IS_FLOAT(expr) _Generic((expr), float: true, default: false)

#define ROUNDF(flt) ( STATIC_ASSERT_EXPR(IS_FLOAT(flt), "Wrong argument " #flt " passed to ROUNDF, expected float.") \
                      , /* comma operator */           \
                      ((flt)-(uint32_t)flt > 0.5f ?    \
                      (uint32_t)flt+1 :                \
                      (uint32_t)flt )                  \
                    )

int main()
{
  printf("%"PRIu32 "\n", ROUNDF(3.14f));
  printf("%"PRIu32 "\n", ROUNDF(3.54f));
  printf("%"PRIu32 "\n", ROUNDF(3.14)); // compiler error
  printf("%"PRIu32 "\n", ROUNDF(3.54)); // compiler error
  printf("%"PRIu32 "\n", ROUNDF(3));    // compiler error
}
History

2 comment threads

Round half to even (1 comment)
Why can't you just add 0.5 before converting to integer? (2 comments)
+0
−0

I know you asked specifically about the C preprocessor, but I'm going to mention my own MPASM and ASM30 preprocessor anyway. It is called PREPIC, and is free and open source (in the Embed PIC repository on GitHub). PREPIC is actually a thin layer over the Embed generic scripting and preprocessing engine, ESCR. That's also free and open source.

This preprocessor is significantly more capable than the one that comes with C compilers. It doesn't just do string substitution hacks, but has native variables, constants, in-line functions, subroutines, and more of its own. Here is an example of using PREPIC with ASM30 to create the value Pi rounded to the nearest fixed point with 8 fraction bits, then load the result into W0 of a dsPIC:

/var r new real              ;create preprocessor variable R
/set r [pi 256]              ;set R to Pi times 256
/const pifix integer = [rnd r] ;create constant PIFIX

         mov     #[v pifix], w0 ;fixed point Pi into W0

Note that R is a preprocessor variable, and that it specifically has the type REAL (floating point). PIFIX is a preprocessor constant and has the type INTEGER.

Expressions in square brackets are preprocessor functions. These get expanded to their value before the assembler sees the code. The first token of each function is the function name. The PI function returns the value of Pi times the (optional) parameter. The RND function converts floating point to integer by rounding. Yes, there is also a TRUNC function. The V function returns the value of the argument. That's how the fixed point value of Pi is ultimately moved into the assembler domain.

The above example was more verbose than needed to illustrate a few points. It could have been:

/const pifix integer = [rnd [pi 256]] ;create constant PIFIX

         mov     #[v pifix], w0 ;fixed point Pi into W0

Or if the fixed point value of Pi is only used in this one place, it could have been:

         mov     #[rnd [pi 256]], w0 ;fixed point Pi into W0

ESCR is intended to allow applications (like PREPIC) to use it as a preprocessor and customize some of its features. This could be done to create a C preprocessor. C already reserves "#" for identifying preprocessor commands. The hard part would be deciding the syntax for identifying preprocessor inline functions. It would probably have to be a two-character sequence. Another possibility is that an ESCR C preprocessor only produces specific #DEFINE C macros as its output, which are then handled in the usual way. In other words, there wouldn't be any ESCR in-line functions except within ESCR preprocessor commands.

History

0 comment threads

+0
−0

If you can truncate (get the floor() of a number), then you can round the number by adding 0.5 first. Or, I suppose that, for the sake of completeness, you add "the equivalent of 0.5," since a given program might not represent the values in decimal or you might want to round to a non-ones position in the number.

When you round numbers (and you know this, otherwise you wouldn't make the distinction, but to explain beyond "add a half"), a (decimal) digit of five or higher bumps the next-most-significant place up by one, otherwise you round. Assuming rounding to the nearest integer, then, from 0.0 to 0.49̅, adding 0.5 increases to 0.5 to 0.99̅, so truncation goes to the lower value. Anything higher crosses the threshold to the next integer, so truncation gives you that higher value.

History

1 comment thread

Compile-time (3 comments)

Sign up to answer this question »