Home > Blockchain >  Binomial Theorem function does not return the expected value
Binomial Theorem function does not return the expected value

Time:09-27

I would like to know why my output returns 1250 instead of the expected output 4096? My input for x: 3, y:4 , n: 5. I have already created a factorial function which is not shown below

int main(){
    float x,y,n,factSum,bi;
    
    printf("Enter value of x: ");
    scanf("%f", &x);
    printf("\nEnter value of y: ");
    scanf("%f", &y);
    printf("\nEnter value of n: ");
    scanf("%f",&n);

    for (int k = 0; k<n; k  )
    {
        factSum = (factorial(n) / (factorial(k) * (factorial(n-k))));
        bi = factSum * powf(x,(n-k)) * powf(y,k);
        bi  = bi;
    }
    printf("\nBinomial Theorem is %f",bi);

    Return 0;
}

CodePudding user response:

There are two major mistakes here:

  1. Incorrect implementation of the binomial expansion calculation. The variable k must span from 0 to n, however you have k go from 0 to n-1.

  2. Summation in the variable bi. You re-assign the variable before you sum it, meaning you do not keep a running sum at all. Your line 14 should read:

    bi  = factSum * powf(x,(n-k)) * powf(y,k);
    

    and the subsequent line 15 should be removed.

Here is a complete and correct minimal example, with some variables renamed to better reflect what they actually represent:

#include <stdio.h>
#include <math.h>

unsigned factorial(unsigned n)
{
    unsigned partial_product = 1;
    while (n > 1)
        partial_product *= n--;
    return partial_product;
}

int main(){
    float x, y, n;
    float binom_coeff;
    float partial_sum = 0;

    printf("Enter value of x: ");
    scanf("%f", &x);
    printf("Enter value of y: ");
    scanf("%f", &y);
    printf("Enter value of n: ");
    scanf("%f", &n);

    for (unsigned k = 0; k <= n;   k) {
        binom_coeff = (factorial(n) / (factorial(k) * (factorial(n-k))));
        partial_sum  = binom_coeff * powf(x, (n-k)) * powf(y, k);
    }

    printf("Binomial expansion calculation of (%g %g)^%g = %g\n", x, y, n, partial_sum);

    return 0;
}

compile with something like cc binthm.c -lm.

A sample run should produce something like:

Enter value of x: 3
Enter value of y: 4
Enter value of n: 5
Binomial expansion calculation of (3 4)^5 = 16807

which is easily verifiable on a calculator.

  •  Tags:  
  • c
  • Related