0

I have several variables listed below:

int cpu_time_b  = 6
float clock_cycles_a = 2 * pow(10, 10));
float cpi_a = 2.0;
int cycle_time_a = 250;
float cpi_b = 1.2;
int cycle_time_b = 500 

I am working out the clock rate of b with the following calculation:

(((1.2*clock_cycles_a)/cpu_time_b)/(1 * pow(10, 9)))

Clearly the answer should be 4 however my program is outputting 6000000204800000000.0 as the answer

I think that overflow is possibly happening here. Is this the case and if so, how could I fix the problem?

6
  • 4
    Where's cpu_time_b defined? Commented Oct 23, 2013 at 14:27
  • 1
    Well the first point of action would be to use datatypes that can handle larger numbers, like double, or even long double if supported. Commented Oct 23, 2013 at 14:29
  • 1
    Other than screaming warnings about converting double to float, it works fine for me. Result I get is 1.6. Commented Oct 23, 2013 at 14:36
  • 1
    Running your problem (after including the missing ; ) gives 1.6 for me. How do you print the result? Commented Oct 23, 2013 at 14:37
  • Btw: I think it is more effective to write 1e9 instead of pow(10,9). Commented Oct 23, 2013 at 14:41

1 Answer 1

1

All calculations should be made to ensure comparable numbers are "reduced" together. in your example, it seems like only

cpu_time_b

is truly variable (undefined in the scope of your snippet. All other variables appears as constants. All constants should be computed before compilation especially if they are susceptible to cause overflow.

clock_cycles_a

cancels the denominator. pow is time consuming (may not be critical here) and not always that precise. You multiply the 2 explicitly when you declare clock_cycles_a and then use 1.2 below. etc. Reducing the whole thing keeping only the actual variable becomes:

24.0/cpu_time_b

which makes me deduce that cpu_time_b should be 6?

Finaly, while you write the equation, we have no idea of what you do with the result. Store it in the wrong variable type? printf with the wrong format? etc?

Sign up to request clarification or add additional context in comments.

2 Comments

Although the variables are not used in this snippet of code they are used throughout my actual program. The result of the calculation is being printed within a printf statement
Of all the "variables" above where you asign a constant, do these values varies throughout the execution? if not, they should be actual constants.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.