This question already has answers here:
Why I am getting zero in float expressions like 1/2? [duplicate]
(2 answers)
Closed 5 years ago.
I have the following code in a header file for an AVR32 program I'm writing:
#define PULSE_FREQ 150
#define TC_FREQ (60000000 / 8)
#define PULSE_PER (1 / PULSE_FREQ)
#define TC_PER (1 / TC_FREQ)
#define TTC ((PULSE_PER / TC_PER) - 1)
The goal is to be able to give a frequency and calculate the constant timer count value given by this formula:
Target Count = ((1 / Target Frequency) / (1 / Timer Frequency)) - 1
For example, for a timer frequency of 150Hz, a timer count value of 49999 is required. When manually entering that value for the timer, it works and gives a frequency of 150Hz. However, when using the code above, I get a frequency of 57Hz.
I'm also getting warnings about a division by zero, could the numbers in the constants be so small that they're getting chopped off to zero?
Would it be better to go about this at runtime instead of with #define macros?
The integer division is probably returning a number less than 1 at some point, and it's being truncated to 0.
Try forcing floating-point division by making one of the constants a double:
// The .0 should "infect" the other numbers
#define PULSE_FREQ 150.0
#define TC_FREQ (60000000 / 8)
#define PULSE_PER (1 / PULSE_FREQ)
#define TC_PER (1 / TC_FREQ)
#define TTC ((PULSE_PER / TC_PER) - 1)
Related
This question already has answers here:
Integer division returns 0 in C
(2 answers)
Closed last year.
I wanted to get the convert from Fahrenheit to Celsius with this program, but it always returns 0. Why?
#include <stdio.h>
int main() {
int fahr = 15, celsius;
celsius = (5 / 9) * (fahr - 32);
printf("%d\n", celsius);
return 0;
}
It seems that the problem is in celsius = (5 / 9) * (fahr - 32);. I already know that celsius = 5 * (fahr - 32) / 9; fixes the problem. But why did the first one return zero?
In short, when performing arithmetic operations, C compiler has to choose which number format to use. To do this, it won't pick the one of the first operand, nor try to guess what the result would be, but will opt for the most precise type of both operand.
In your particular example, (5 / 9) use two integers, so the result will remain an integer too, thus zero.
A quick way to fix this is to directly specify a decimal in your constant :
(5 / 9.0)
The other answers and comments are steering you in the correct direction with regards to integer division vs floating point. But if you want to avoid floating point altogether and still produce a correct answer (as an integer), then structure your equation such that division comes last.
Since (x/y) * z is the same as (x * z)/y, then this holds:
celsius = (5 * (fahr - 32)) / 9;
In C, if you do a division between two integer type variables, you get an integer back.
So this:
(5 / 9)
gets a result of 0.555, which is then rounded down. (In C, integer division rounds towards zero.)
If you changed it like this, it would be floating point division instead:
celsius = (5.0 / 9) * (fahr - 32);
This question already has answers here:
Rounding integer division (instead of truncating)
(26 answers)
Closed 1 year ago.
I need to know the price of all the offices that a company hires, knowing that you pay per office and there can be room for two workers per room, the problem is that I cannot use libraries or if...
monthlyPrice = oficePrice * (workers/2);
monthlyPrice = 100 * (7 / 2) = 350$
I need to either round up or find me another mathematical formula.
it could be done with a realtointegrer, i donĀ“t now... :(
Thanks. Pablo.
The simpliest way to round a floating point number x is as follows:
return (int)(x + 0.5);
I would suggest that you use the / and % operators.
/ will give you the integer section (left side of decimal point) for a division operation.
% will give you the remainder section (right side of the decimal point) of a division operation.
e.g.
7/2 gives 3
7%2 gives 1
You can then decide whether you wish to round up the result depending on the value returned by using %.
Ah I see that you're not allowed to use the if ... else ... construct. What about ... ? ... : ...?
For money I would use fixed point.
//one cent is minimum we care
#define MULT (100)
#define MAKE_FIXED(d) ((int32_t)(d * MULT))
#define MAKE_REAL(f) (((double)(f)) / MULT)
int32_t mulf(int32_t a, int32_t b)
{
int64_t part = (int64_t)a * b;
return part/MULT;
}
int32_t divf(int32_t a, int32_t b)
{
int64_t part = ((int64_t)a * MULT) / b;
return part;
}
int main(void)
{
int32_t officeprice = MAKE_FIXED(100);
int32_t workers = MAKE_FIXED(7);
printf("%f\n", MAKE_REAL(mulf(officeprice, divf(workers,MAKE_FIXED(2)))));
}
This question already has answers here:
C macros and use of arguments in parentheses
(2 answers)
Closed 1 year ago.
I'm a beginner in programming and I have a question. Mainly, what is the difference in defining PI exactly as I state below;
#define PI (4.*atan(1))
#define PIa 4.*atan(1)
#define PIb 4*atan(1)
I have printed this code:
printf( "%lf\n", 3 / PI );
printf( "%lf\n", 3 / PIa );
printf( "%lf\n", 3 / PIb );
The results are:
0.954930
0.589049
0.000000
According to my calculator the first one is correct, and the rest should also be.
Why aren't they?
The macro is text substitution thus:
3 / PIa
is parsed as:
3 / 4.*atan(1) = (3/4.) * atan(1)
This is different from the first case where 3 / PI is expanded as:
3 / (4.*atan(1))
The similar case is for the third example:
3 / 4*atan(1) = (3/4) * atan(1)
The expression 3/4 is integer division, which result is 0.
Generally, it is strongly advised to put parentheses around the whole macro and all parameters it takes like in the following example:
#define ADD(a,b) ((a) + (b))
There are various macro-based solutions out there to compute the integer-valued log2 at compile time, but what if you need a bit more precision than what you get with integers, i.e. a few binary places after the binary point? It doesn't matter whether the value generated is a floating point expression, or a fixed-point scaled integer expression, as long as it evaluates to a compile-time constant value.
What is this useful for, you may ask? The application I had in mind was to compute the number of bits needed to optimally pack a structure whose fields have value sets that don't span a power of 2 range.
I've come up with the following - it's not particularly inventive, but it works, and doesn't slow the compilation totally to a crawl. IOW, it does what I needed it to do - add a couple (here: dozen) binary places' worth of precision after the binary point.
It works by representing the number as a power of 2 and trial-multiplying it by coefficients that happen to have log2 values equal to a binary fraction (2^-n). Multiplying by such coefficients is equivalent to adding together the logarithms, and thus the FRAC_LOG2 macro expands to a sum with elements selected with nested ternary expressions.
#define IROOT2_1 .7071067812 // 2^-(2^-1)
#define IROOT2_2 .8408964153 // 2^-(2^-2)
#define IROOT2_3 .9170040432 // 2^-(2^-3)
#define IROOT2_4 .9576032807 // 2^-(2^-4)
#define IROOT2_5 .9785720621 // 2^-(2^-5)
#define IROOT2_6 .9892280132 // 2^-(2^-6)
#define IROOT2_7 .9945994235 // 2^-(2^-7)
#define IROOT2_8 .9972960561 // 2^-(2^-8)
#define IROOT2_9 .9986471129 // 2^-(2^-9)
#define IROOT2_A .9993233275 // 2^-(2^-10)
#define IROOT2_B .9996616065 // 2^-(2^-11)
#define IROOT2_C .9998307889 // 2^-(2^-12)
#define BIT_SCAN_REV(n) \
(n>>15?15:n>>14?14:n>>13?13:n>>12?12:n>>11?11:n>>10?10:n>>9?9:\
n>>8?8:n>>7?7:n>>6?6:n>>5?5:n>>4?4:n>>3?3:n>>2?2:n>>1?1:0)
#define FRAC_LOG2_1(m,n) (1./4096.)*\
((m<=n*IROOT2_1?2048:0)+FRAC_LOG2_2(m,n*(m<=n*IROOT2_1?IROOT2_1:1)))
#define FRAC_LOG2_2(m,n) ((m<=n*IROOT2_2?1024:0)+FRAC_LOG2_3(m,n*(m<=n*IROOT2_2?IROOT2_2:1)))
#define FRAC_LOG2_3(m,n) ((m<=n*IROOT2_3?512:0)+FRAC_LOG2_4(m,n*(m<=n*IROOT2_3?IROOT2_3:1)))
#define FRAC_LOG2_4(m,n) ((m<=n*IROOT2_4?256:0)+FRAC_LOG2_5(m,n*(m<=n*IROOT2_4?IROOT2_4:1)))
#define FRAC_LOG2_5(m,n) ((m<=n*IROOT2_5?128:0)+FRAC_LOG2_6(m,n*(m<=n*IROOT2_5?IROOT2_5:1)))
#define FRAC_LOG2_6(m,n) ((m<=n*IROOT2_6?64:0)+FRAC_LOG2_7(m,n*(m<=n*IROOT2_6?IROOT2_6:1)))
#define FRAC_LOG2_7(m,n) ((m<=n*IROOT2_7?32:0)+FRAC_LOG2_8(m,n*(m<=n*IROOT2_7?IROOT2_7:1)))
#define FRAC_LOG2_8(m,n) ((m<=n*IROOT2_8?16:0)+FRAC_LOG2_9(m,n*(m<=n*IROOT2_8?IROOT2_8:1)))
#define FRAC_LOG2_9(m,n) ((m<=n*IROOT2_9?8:0)+FRAC_LOG2_A(m,n*(m<=n*IROOT2_9?IROOT2_9:1)))
#define FRAC_LOG2_A(m,n) ((m<=n*IROOT2_A?4:0)+FRAC_LOG2_B(m,n*(m<=n*IROOT2_A?IROOT2_A:1)))
#define FRAC_LOG2_B(m,n) ((m<=n*IROOT2_B?2:0)+FRAC_LOG2_C(m,n*(m<=n*IROOT2_B?IROOT2_B:1)))
#define FRAC_LOG2_C(m,n) (m<=n*IROOT2_C?1:0)
#define FRAC_LOG2(n) (BIT_SCAN_REV(n) + FRAC_LOG2_1(1<<BIT_SCAN_REV(n), n))
It's not exactly cheap, of course - for a 2-digit number, it expands to about 700kb of code that the compiler has to dig through, but it has precision of over 5 fractional decimal digits.
A work around is to store the integral result of BIT_SCAN_REV in an enum, so that it's just a couple letters instead of about 170:
enum {
input = 36,
bsr = BIT_SCAN_REV(input),
bsr_ = 1<<bsr_,
};
static const float output = bsr + FRAC_LOG2_1(bsr_, input);
Another way of doing this at a much lower memory cost, without recursive macros, would require an include file to be used any time a value is to be computed.
This question already has answers here:
Are constant C expressions evaluated at compile time or at runtime?
(9 answers)
Closed 4 years ago.
I was perusing some kernel source code from cpufreq_governor.h and saw this:
/*
* The polling frequency depends on the capability of the processor. Default
* polling frequency is 1000 times the transition latency of the processor. The
* governor will work on any processor with transition latency <= 10ms, using
* appropriate sampling rate.
*
* For CPUs with transition latency > 10ms (mostly drivers with CPUFREQ_ETERNAL)
* this governor will not work. All times here are in us (micro seconds).
*/
#define MIN_SAMPLING_RATE_RATIO (2)
#define LATENCY_MULTIPLIER (1000)
#define MIN_LATENCY_MULTIPLIER (20)
#define TRANSITION_LATENCY_LIMIT (10 * 1000 * 1000)
Would it not be more efficient to change the last line to read:
#define TRANSITION_LATENCY_LIMIT (10000000) /* (10 * 1000 * 1000) */
Would it not be more efficient to change the last line to read:
#define TRANSITION_LATENCY_LIMIT (10000000) /* (10 * 1000 * 1000) */
Most probably it wouldn't make any difference.
Any half-decent compiler should be able to calculate 10 * 1000 * 1000 at compilation time.
Ask yourself:
how many zeros are there in your suggestion (or alternative, what is the number)
#define TRANSITION_LATENCY_LIMIT (10000000)
Tiring task. This is a lot more intuitive and easy (and easy to maintain):
#define TRANSITION_LATENCY_LIMIT (10 * 1000 * 1000)
Also, (10 * 1000 * 1000) is more convenient way to represent 10 microseconds (10 times 1 millionth (1000 * 1000) of a second)
Also, no efficiency matter here as it will be computed by compiler.
No doubt you change it and get more efficient code because multiplication is take more CPU cycle comparison to addition and subtraction but you loss code readability of your source code. but don't wary today's compiler is so smart and done it you for compile time and this process is know as code optimization.