# STM publishing: tools, technologies and changeA WordPress site for STM Publishing

26Aug/14Off

## TeX’s “badness” function in C

TeX uses the concept of "badness" as a measure of how much the glue in a box has to stretch or shrink. In the following C function, t is the difference between the total of the natural sizes (N) of the components in the box and the desired size of the box (d). So, t = N-d. If the total amount of glue available for stretching or shrinking is s, then the badness, according to the TeXbook, is $100(t/s)^3$ – note that t/s is also known as the glue-set-ratio (often denoted r). In reality, TeX uses an approximation to this calculation, as shown below – the C code is from the C output by Web2C.

typedef int scaled  ;
typedef int halfword  ;

halfword badness ( scaled t , scaled s )
{
halfword Result;
integer r  ;
if ( t == 0 )
Result = 0 ;
else if ( s <= 0 )
Result = 10000 ;
else {
if ( t <= 7230584L )
r = ( t * 297 ) / s ;
else if ( s >= 1663497L )
r = t / ( s / 297 ) ;
else r = t ;
if ( r > 1290 )
Result = 10000 ;
else Result = ( r * r * r + 131072L ) / 262144L ;
}
return Result ;
}