Finding the runtime of a segment of code in C - c

The below code should find the runtime in seconds of the for loop. Looking at other resources this should do the trick, having an initial clock() subracted from a clock() after the for loop runs. Any ideas why the code isn't working as written?
#include <stdio.h>
#include <time.h>
//prototypes
int rfact(int n);
int temp = 0;
main()
{
int n = 0;
int i = 0;
double result = 0.0;
clock_t t;
printf("Enter a value for n: ");
scanf("%i", &n);
printf("n=%i\n", n);
//get current time
t = clock();
//process factorial 2 million times
for(i=0; i<2000000; i++)
{
rfact(n);
}
printf("n=%i\n", n);
//get total time spent in the loop
result = (double)((clock() - t)/CLOCKS_PER_SEC);
//print result
printf("runtime=%d\n", result);
}
//factorial calculation
int rfact(int n)
{
if (n<=0)
{
return 1;
}
return n * rfact(n-1);
}

result = (double)((clock() - t)/CLOCKS_PER_SEC);
This should be:
result = ((double)(clock() - t))/CLOCKS_PER_SEC;
Otherwise, you're doing integer division and converting the result to a double, which is not what you want.
Also:
printf("runtime=%d\n", result);
Should be:
printf("runtime=%f\n", result);

Related

why does the value of this factorial change when called by a function that SHOULD calculate the value of e

#include <stdio.h>
#include <math.h>
int main()
{
double precision = 0;
printf("\ninsert number\n");
while(precision < 1){
scanf("%lf",&precision);
}
printf("the value of e with precision of %.0lf is %lf",precision,e(precision));
return 0;
}
int fact(int num){
int ris = 1;
for(int i = num;i > 0;i--){
ris = ris * i;
}
printf("res=%d\n",ris);
return ris;
}
int e(double precision){
double valE = 1;
for(double i = precision;i > 0 ;i--){
valE = valE + 1/fact(i);
printf("\nsame res:%.1lf\n",fact(i));
}
return (double)valE;
}
debug
i know there is an answer for that but my problem is the comunication between the 2 functions, i know i could solve it by slapping everything inside the main()
There are many issues:
format specifiers (for scanf and printf) must match the arguments
don't use floating point types as counters
if you divide one integer by another integer, the result will be an integer that is trucated. If you want the result to be a floating point type, you need to convert at least one of the operands to a floating point type.
you need to declare the functions you use (fact and e) before using them, or just put them before main, like below.
You want this, explanations in the comments:
#include <stdio.h>
#include <math.h>
int fact(int num) {
int ris = 1;
for (int i = num; i > 0; i--) {
ris = ris * i;
}
printf("res=%d\n", ris);
return ris;
}
double e(int precision) {
double valE = 1;
for (int i = precision; i > 0; i--) { // use int for loop counters
valE = valE + 1.0 / fact(i); // use `1.0` instead of `1`, otherwise an
// integer division will be performed
printf("\nsame res: %d\n", fact(i)); // use %d for int^, not %llf
}
return valE; // (double) cast is useless
}
// put both functions e and fact before main, so they are no longer
// declared implicitely
int main()
{
int precision = 0; // precision should be an int
printf("\ninsert number\n");
while (precision < 1) {
scanf("%d", &precision); // use %d for int
}
printf("the value of e with precision of %d is %lf", precision, e(precision));
return 0;
}

Calculate sin(x) and cos(x) using Taylor Series in C [duplicate]

I have been struggling with this code and just do not seem to grasp what I am doing wrong.
The code is suppose to calculate : Sum of a series of "Cosine" with pattern [(-1)^i(x)^2i]/(2i)!
Here is my code thus far:
#include <stdio.h>
#include <math.h>
float factorial(int n){
if (n==0)
return 1;
else
return 2*n*factorial(n-1);
}
int main (){
float i, n;
float sum=0;
printf("Enter desired interger: ");
scanf("%f", &n);
for (i=0; i<=1; i++)
sum = sum + (pow(-1,i)*pow(n,2*i))/(factorial(n));
printf("The value is %f\n", sum);
return 0;
}
I still working on it, any info or help will be much appreciated!
edit:
Just fixed it guys, this is new format I had to use for my professor:
#include <stdio.h>
#include <math.h>
int factorial(int n)
{
if (n==0) return 1;
else
return n*factorial(n-1);
}
float mycos(float x)
{
float sum=0;
int i;
for (i=0;i<=10;i++) sum = sum + (pow(-1,i)*pow(x,2*i))/factorial(2*i);
return sum;
}
int main()
{
int i=1;
printf(" x mycos(x) cos(x)\n");
for (i=1;i<=10;i++)
printf(" %f %f %f\n", i*.1, mycos(i*.1), cos(i*.1));
return 0;
}
Thank you all for your explanations, they helped out Immensely!
One thing I see, is that your for loop within main only runs through 2 real iterations, once for i == 0, and again for i == 1.
For the taylor expansion to work fairly effectively, it needs to be run through more sequence terms (more loop iterations).
another thing I see, is that your denominator is the n! rather than (2 * n)!
For efficiency, I might also implement the factorial routine as follows:
unsigned int factorial(int n){
unsigned int product = 1;
for(int I = 1; I <= n; I++) product *= I;
return product;
}
The above factorial routine is for a more EXACT factorial calculation, which perhaps you don't need for this purpose. For your purposes, perhaps the floating point variant might be good enough.
float factorial(int n){
float product = 1;
for(int I = 1; I <= n; I++) product *= (float)I;
return product;
}
I should also note why I am stating to perform factorial in this manner. In general a loop construct will be more efficient than its recursive counterpart. Your current implementation is recursive, and thus the implementation I provide SHOULD be quite a bit more efficient from both performance, and memory utilization.
Considering computation expense, you need to stop calculating the series at a point. The more you go, the more precise the result will be, but the more your program spends time. How about this simple program:
#include <stdio.h>
#include <math.h>
#define ITERATIONS 10 //control how far you go
float factorial(int n){
if (n==0)
return 1;
else
return n*factorial(n-1);
}
int main (){
float n;
float sum=0;
printf("Enter desired float: ");
scanf("%f", &n);
int c, i;
for (i=0; i<=ITERATIONS; i++) {
c = (i%2)==0? 1 : -1;
sum = sum + (c*pow(n,2*i+1))/(factorial(2*i+1));
}
printf("The value is %f\n", sum);
return 0;
}
1.) You are only multiplying even no.s in factorial function return 2*n*factorial(n-1); will give only even no.s. Instead you can replace n with 2n here- sum = sum + (pow(-1,i)*pow(n,2*i))/(factorial(2n)); This will give the correct (2n!).
2.) Check for the no, of iterations for (i=0; i<=1; i++) this will only run your loop twice. Try more no. of iterations for more accurate anwer.
Why are you calculating power etc for each item in the series? Also need to keep numbers in a suitable range for the data types
i.e. for cos
bool neg_sign = false;
float total = 1.0f;
float current = 1.0f;
for (int i = 0; i < length_of_series; ++i) {
neg_sign = !neg_sign;
current = current * (x / ((2 * i) + 1)) * (x / (( 2 * i) + 2));
total += neg_sign ? -current : current;
}
EDIT
Please see http://codepad.org/swDIh8P5
#include<stdio.h>
# define PRECISION 10 /*the number of terms to be processed*/
main()
{
float x,term=1,s=1.0;
int i,a=2;
scanf("%f",&x);
x=x*x;
for(i=1;i<PRECISION;i++)
{
term=-term*x/(a*(a-1));
s+=term;
a+=2;
}
printf("result=%f",s);
}
Your factorial() function actually calculates 2n.n!, which probably isn't what you had in mind. To calculate (2n)!, you need to remove the 2* from the function body and invoke factorial(2*n).

error - time executing in C

I'm working in first step of a Project and I have to calculate the executing time of a Summation and a multiplication... I wrote the next code for the summation:
#include <stdio.h>
#include <time.h>
int main(int argc, char const *argv[]) {
long muestras = 100000000;
long resultado=0;
float inicial = clock();
printf("Tiempo inicial: %f\n",inicial);
for(int i = 1; i <muestras;i+=1){
resultado = resultado + i;
}
float final = clock();
printf("Tiempo final: %f\n",final);
float total = (final-inicial)/((double)CLOCKS_PER_SEC);
printf("tiempo = %f",total);
//printf("tiempo = %f",((double)clock() - start));
printf("\n");
printf("resultado = %d",resultado);
return 0;
}
and work perfectly, but I wrote the next code for the multiplication, and the initial and final time is 0... I don't know why, I can't understand ...
#include <stdio.h>
#include <time.h>
int main(int argc, char const *argv[]) {
long muestras = 10;
long long resultado=1;
float inicial = clock();
printf("Tiempo inicial: %f\n",inicial);
for(int i = 1; i <muestras;i+=1){
if (resultado>20) {
resultado = (resultado * i)/20;
}else{
resultado = resultado * i;
}
}
float final = clock();
printf("Tiempo final: %f\n",final);
float total = (final-inicial);
///((double)CLOCKS_PER_SEC);
printf("tiempo = %f",total);
//printf("tiempo = %f",((double)clock() - start));
printf("\n");
printf("resultado = %lli",resultado);
return 0;
}
I know that have overflow, but no matter what size of samples take, it's the same result.... please help ... sorry for my bad english, greats from Colombia! :)
The return value from clock is of type clock_t, not float. Also, the return value is not seconds or anything such, but "clocks", which you can convert to seconds by dividing by clocks per sec.
You should do something like this instead:
clock_t initial = clock();
...
clock_t final = clock();
double total = (final - initial) / (double)CLOCKS_PER_SEC;
printf("time delta = %f", total);
Note that there is no way of printfing a value of type clock_t correctly.
The return value from clock() is of type clock_t not float, and it represents the number of ticks since the beginning of the program. You should subtract them and then convert to double to divide by CLICKS_PER_SEC, as in Antti's answer.
Also, your multiplication program only executes 10 muestras, which means it may entirely finish in the first clock tick. Increase that to a large number and you may see different elapsed time.

quadratic Sum of N nummbers: implementation in C

As you can read in the header it is about a rather simple topic. But I encountered something very odd while implementing possible different ways to get a quadratic sum of N numbers.
I implemented three different versions:
Quadratic Gauß sum (func: quadratGauss(int n) )
Iterative (func: quadratIterativeClassic(int n) )
Iterative via Bitoperation (func: quadratIterativeBitoperation(int n) )
All three functions have returned the same result as expected from the given Input. The Big question now is. How was it possible for the third function to work proper? The Code looks like this:
void quadratGauss(int n){
printf("+quadratGauss: \n");
int result = ((n*(n+1))*(2*n+1))/2;
printf("Result: %d\n----------------\n",result);
}
void quadratIterativClassic(int n){
int result;
printf("+quadratIterativClassic: \n");
for(int i;i<=n;i++)
result += i * i;
printf("Result: %d\n----------------\n",result);
}
void quadratIterativeBitOperation(int n){
int result;
printf("+quadratIterativeBitOperation: \n");
for(int i;i<=n;i++)
result += i^2;
printf("Result: %d\n----------------\n",result);
}
As you see I use the XOR operator. I originally wanted to use the shift-operator "<<" but i tried others as well. what where stunning when i tried the XOR operator: the result was still the same as before and the same as the other two functions. I thought this was not possible because the XOR is not an operator for the power-operation because C does not contain such an operator but still i got eventually the right result.
I tested the functions with different numbers of different "sizes". Nothing odd in the result of each function.
I've got no clue why. But there must be an explanation, doesn't it?
If you have one, I would appreciate alot the effort of writing down a possible reason, why you can implement this with the XOR operator.
here the whole main file:
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#define N 5000
void sumGauss(int n)
{
printf("+sumGauss: \n");
int result = (n*(n+1)/2);
printf("Result: %d\n----------------\n",result);
}
void sumClassic(int n)
{
printf("+sumClassic: \n");
int result = 0;
for(int i = 0; i <= n; i++)
result += i;
printf("Result: %d\n----------------\n",result);
}
void quadratGauss(int n){
printf("+quadratGauss: \n");
int result = ((n*(n+1))*(2*n+1))/2;
printf("Result: %d\n----------------\n",result);
}
void quadratIterativeBitOperation(int n){
int result;
printf("+quadratIterativeBitOperation: \n");
for(int i;i<=n;i++)
result += i^2;
printf("Result: %d\n----------------\n",result);
}
void quadratIterativClassic(int n){
int result;
printf("+quadratIterativClassic: \n");
for(int i;i<=n;i++)
result += i * i;
printf("Result: %d\n----------------\n",result);
}
void unevenSum(int n)
{
printf("+unevenSum: \n");
int uneven = 0;
int i=0;
for(i=1;i<= n;i+=2) {
uneven += i;
}
printf("Result: %d\n----------------\n",uneven*2);
}
void unevenSumModulo(int n)
{
printf("+unevenSumModulo: \n");
int result=0;
for(int i=0;i<=n;i++)
{
if( (i%1) == 0)
result += i;
}
printf("Result: %d\n----------------\n",result);
}
void unevenSumNico(int n)
{
printf("+unevenSumNico: \n");
int odd = 0;
int i=0;
for(i=1;i<= n;i++) {
odd += ((2*i)-1)/2;
}
printf("Result: %d\n----------------\n",odd);
}
void evenSum(int n)
{
printf("+evenSum: \n");
int result=0;
for(int i=0;i<=n;i++)
{
if( (i%2) == 0)
result += i;
}
printf("Result: %d\n----------------\n",result);
}
void Zins(float Kapital,int years)
{
printf("Zinstabelle fuer Grundkaptial %.2f Euro\n",Kapital);
printf("Kapitalstand zum Jahresende\n");
int i=0;
float K = Kapital;
for(int i =1;i<years+1;i++)
{
K = K *(1.f + 0.05f);
printf("Jahr: %2d Kapital: %.2f Euro\n",i,K);
}
}
int main(int argc, char** argv) {
sumGauss(N);
sumClassic(N);
quadratGauss(N);
quadratIterativeBitOperation(N);
quadratIterativClassic(N);
unevenSum(N);
unevenSumNico(N);
unevenSumModulo(N);
evenSum(N);
Zins(N);
return 0;
}
This would only be true for n = 0. Rest assured that you cannot implement squaring using just the XOR operator, even for integral types.
The behaviour of your code is currently undefined, as you don't initialise either i, or result. I suspect that your loop does not run at all and by the most amazing coincidence, result occupies the same memory in the subsequent functions as it does in the Guassian function. But don't ever rely on that behaviour. Other compilers might simply attempt to eat your cat.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char const *argv[]){
int i=0,n1;
scanf("%d",&n1);
void quadratGauss(int n){
printf("+quadratGauss: \n");
int result = ((n*(n+1))*(2*n+1))/6; // you made here mistake take 2 insted of 6.
printf("Result: %d\n----------------\n",result);
}
void quadratIterativClassic(int n){
int result=0;
printf("+quadratIterativClassic: \n");
for(i=1;i<=n;i++)
result += i * i;
printf("Result: %d\n----------------\n",result);
}
void quadratIterativeBitOperation(int n){
int result=0;
printf("+quadratIterativeBitOperation: \n");
for(i=1;i<=n;i++)
result += pow(i,2); //This is power fun to add series of quadrat
printf("Result: %d\n----------------\n",result);
}
//call the fun.
quadratGauss(n1);
quadratIterativClassic(n1);
quadratIterativeBitOperation(n1);
return 0;
}
:) Want to more about http://www.trans4mind.com/personal_development/mathematics/series/sumNaturalSquares.htm
https://en.wikipedia.org/wiki/Quadratic_Gauss_sum
First, its /6, not /2. See that quadratGauss is always 3 times the quadratIterativClassic. And I got completely different results for quadratIterativeBitOperation
n = 4
+quadratGauss:
Result: 90
----------------
+quadratIterativClassic:
Result: 30
----------------
+quadratIterativeBitOperation:
Result: 12
----------------
n = 5
+quadratGauss:
Result: 165
----------------
+quadratIterativClassic:
Result: 55
----------------
+quadratIterativeBitOperation:
Result: 19
----------------
n = 6
+quadratGauss:
Result: 273
----------------
+quadratIterativClassic:
Result: 91
----------------
+quadratIterativeBitOperation:
Result: 23
I think it your compiler must have ^ set as exponent instead of XOR

Selecting and analysing window of points in an array

Could someone please advise me on how to resolve this problem.
I have a function which performs a simple regression analysis on a sets of point contained in an array.
I have one array (pval) which contains all the data I want to perform regression analysis on.
This is how I want to implement this.
I get an average value for the first 7 elements of the array. This is what I call a 'ref_avg' in the programme.
I want to perform a regression analysis for every five elements of the array taking the first element of this array as the 'ref_avg'. That is in every step of the regression analysis I will have 6 points in the array.
e.g
For the 1st step the ref_avg as calculated below is 70.78. So the 1st step in the simple regression will contain these points
1st = {70.78,76.26,69.17,68.68,71.49,73.08},
The second step will contain the ref_avg as the 1st element and other elements starting from the second element in the original array
2nd = {70.78,69.17,68.68,71.49,73.08,72.99},
3rd = {70.78,68.68,71.49,73.08,72.99,70.36},
4th = {70.78,71.49,73.08,72.99,70.36,57.82} and so on until the end.
The regression function is also shown below.
I don't understand why the first 3 elements of the 'calcul' array have value 0.00 on the first step of the regression, 2 elements on the 2nd step,1 elements on the 3rd.
Also the last step of the regression function is printed 3 times.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
float pval[]={76.26,69.17,68.68,71.49,73.08,72.99,70.36,57.82,58.98,69.71,70.43,77.53,80.77,70.30,70.5,70.79,75.58,76.88,80.20,77.69,80.80,70.5,85.27,75.25};
int count,Nhour;
const int MAX_HOUR = 24;
float *calcul=NULL;
float *tab_time =NULL;
float ref_avg;
int size_hour=7;
float sum=0;
int length = Nhour+1;
float m;
float b;
calcul=(float*)calloc(MAX_HOUR,sizeof(calcul));
if (calcul==NULL)
{
printf(" error in buffer\n");
exit(EXIT_FAILURE);
}
tab_time= calloc(MAX_HOUR,sizeof(float));
/* Get the average of the first seven elements */
int i;
for (i=0;i<size_hour;i++)
{
sum += pval[i];
}
ref_avg = sum / size_hour;
count=0;
/* perform the regression analysis on 5 hours increment */
while(count<=MAX_HOUR)
{
++count;
Nhour=5;
int pass = -(Nhour-1);
int i=0;
for(i=0;i<Nhour+1;i++)
{
if(count<MAX_HOUR)
{
calcul[0]=ref_avg;
calcul[i] =pval[count+pass];
pass++;
}
printf("calc=%.2f\n",calcul[i]); // For debug only
tab_time[i]=i+1;
if(i==Nhour)
{
linear_regression(tab_time, calcul, length, &m, &b);
printf("Slope= %.2f\n", m);
}
}
}
free(calcul);
calcul=NULL;
free(tab_time);
tab_time=NULL;
return 0;
}
/* end of the main function */
/* This function is used to calculate the linear
regression as it was called above in the main function.
It compiles and runs very well, was just included for the
compilation and execution of the main function above where I have a problem. */
int linear_regression(const float *x, const float *y, const int n, float *beta1, float *beta0)
{
float sumx = 0,
sumy = 0,
sumx2 = 0,
sumxy = 0;
int i;
if (n <= 1) {
*beta1 = 0;
*beta0= 0;
printf("Not enough data for regression \n");
}
else
{
float variance;
for (i = 0; i < n; i++)
{
sumx += x[i];
sumy += y[i];
sumx2 += (x[i] * x[i]);
sumxy += (x[i] * y[i]);
}
variance = (sumx2 - ((sumx * sumx) / n));
if ( variance != 0) {
*beta1 = (sumxy - ((sumx * sumy) / n)) / variance;
*beta0 = (sumy - ((*beta1) * sumx)) / n;
}
else
{
*beta1 = 0;
*beta0 = 0;
}
}
return 0;
}
I think this code produces sane answers. The reference average quoted in the question seems to be wrong. The memory allocation is not needed. The value of MAX_HOUR was 24 but there were only 23 data values in the array. The indexing in building up the array to be regressed was bogus, referencing negative indexes in the pval array (and hence leading to erroneous results). The variable Nhour was referenced before it was initialized; the variable length was not correctly set. There wasn't good diagnostic printing.
The body of main() here is substantially rewritten; the editing on linear_regression() is much more nearly minimal. The code is more consistently laid out and white space has been used to make it easier to read. This version terminates the regression when there is no longer enough data left to fill the array with 5 values - it is not clear what the intended termination condition was.
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void linear_regression(const float *x, const float *y, const int n,
float *beta1, float *beta0);
int main(void)
{
float pval[]={
76.26, 68.68, 71.49, 73.08, 72.99, 70.36, 57.82, 58.98,
69.71, 70.43, 77.53, 80.77, 70.30, 70.50, 70.79, 75.58,
76.88, 80.20, 77.69, 80.80, 70.50, 85.27, 75.25,
};
const int Nhour = 5;
const int MAX_HOUR = sizeof(pval)/sizeof(pval[0]);
const int size_hour = 7;
float ref_avg;
float sum = 0.0;
float m;
float b;
float calc_y[6];
float calc_x[6];
/* Get the average of the first seven elements */
for (int i = 0; i < size_hour; i++)
sum += pval[i];
ref_avg = sum / size_hour;
printf("ref avg = %5.2f\n", ref_avg); // JL
/* perform the regression analysis on 5 hours increment */
for (int pass = 0; pass <= MAX_HOUR - Nhour; pass++) // JL
{
calc_y[0] = ref_avg;
calc_x[0] = pass + 1;
printf("pass %d\ncalc_y[0] = %5.2f, calc_x[0] = %5.2f\n",
pass, calc_y[0], calc_x[0]);
for (int i = 1; i <= Nhour; i++)
{
int n = pass + i - 1;
calc_y[i] = pval[n];
calc_x[i] = pass + i + 1;
printf("calc_y[%d] = %5.2f, calc_x[%d] = %5.2f, n = %2d\n",
i, calc_y[i], i, calc_x[i], n);
}
linear_regression(calc_x, calc_y, Nhour+1, &m, &b);
printf("Slope= %5.2f, intercept = %5.2f\n", m, b);
}
return 0;
}
void linear_regression(const float *x, const float *y, const int n, float *beta1, float *beta0)
{
float sumx1 = 0.0;
float sumy1 = 0.0;
float sumx2 = 0.0;
float sumxy = 0.0;
assert(n > 1);
for (int i = 0; i < n; i++)
{
sumx1 += x[i];
sumy1 += y[i];
sumx2 += (x[i] * x[i]);
sumxy += (x[i] * y[i]);
}
float variance = (sumx2 - ((sumx1 * sumx1) / n));
if (variance != 0.0)
{
*beta1 = (sumxy - ((sumx1 * sumy1) / n)) / variance;
*beta0 = (sumy1 - ((*beta1) * sumx1)) / n;
}
else
{
*beta1 = 0.0;
*beta0 = 0.0;
}
}

Resources