Let's make some assumptions. If the polynomial looks like this:
degr
.---
p(x) = > arr[i] * pow(x, i)
`---
i=0
Then, the derivative would be obtained by:
degr
d .---
-- p(x) = > i * arr[i] * pow(x, i-1)
dx `---
i=1
You should be able to compute this with a loop similar to Horner's method.
For your program, you are processing it in several loops, which is unnecessary. But, your first loop is trying to recompute the coefficients. The first coefficient is a constant, so it should be recomputed to zero when the derivative is applied. Instead, you are multiplying by (i+1)
. Just multiply by i
instead.
In your second loop, you understand that the degree has been reduced, but since the first term is 0, you do not have to decrement the degr
variable. You should start the loop from index 1
. Within the body of the for loop itself, the pow
computation should raise to the i-1
power.
In your sum
calculation loop, also start from index 1
.
You should be able to see how the changes I suggested to you came straight from the formula I provided above.
Note, since you modify the array that represents the polynomial, you cannot call the function again to compute the derivative for a different value. You can fix this by modifying the first loop so that the coefficients get stored in arr2
instead, and then changing the second loop so that you are obtaining the coefficients from arr2
. Now, you can declare your input array to be constant in your derv
function.
The code with my suggested changes looks like:
float derv(int degr,const int arr[],float t)
{
int i,n;
float sum=0;
float arr2[degr+1];
for (i=0;i<degr+1;i++) {
arr2[i]=(arr[i]*i);
}
for (i=1;i<degr+1;i++)
{
arr2[i] = (pow(t,i-1)*arr2[i]);
}
for(n=1;n<degr+1;n++)
{
sum = sum + arr2[n];
}
return sum;
}