Taylors Theorem C - c

I've got simple code for Taylor's Theorem for cosh() function.
I'm trying to catch a mistake - the result is sometimes close the real answer.
How to do it correctly?
When my start is 0, end is 5, and subdivides is 5 it gave good results, but when I put 5 as start and 10 as end, the result is farther away from the expected value.
#include <stdio.h>
#include <math.h>
int poww( float number, int a )
{
float result = 1.0;
int i;
if( a != 0 );
{
for( i = 0; i < a; i++ ) {
result = result * number;
}
}
return result;
}
int factorial(int n)
{
switch (n) {
case 0:
return 1;
break;
default:
return n * factorial(n-1);
}
}
void main()
{
puts("Enter start: ");
float start;
scanf("%f", &start);
puts("\nEnter end: ");
float end;
scanf("%f", &end);
puts("\nSubintervals:");
int subinterval;
scanf("%d", &subinterval);
float h = (end - start) / (float)subinterval;
printf("h is : %3.2f \n", h);
double x, result, temp;
int n;
for( x = start; x <= end; x += h) {
result = 0;
for(n = 0 ; ; n++) {
temp = poww(x, 2 * n) / (factorial( 2 * n ) * 1.0);
if(temp < 0.00001) {
break;
} else {
result = result + temp;
printf("X = %f temp = %f, result = %f\n", x, temp, result);
}
}
printf("X = %f, result = %3.2f, cosH = %3.2f\n\n", x, result, cosh(x) );
}
puts("Press any key...");
getchar();
}
PROBLEM SOLVE:
function returns an integer instead of double, also I changed every float to double.

Change all float types to double and use double as the return type for the factorial() and poww() functions, too. It's the last two that are most important in this case.
Also, the return type on main() should be int, not void.
[I just finished removing the dead if statement in poww(), and noticed that the function only "speeds up" a pow() computation. If you're worried about performance, worry about computing a factorial and a power on every term, rather than multiplying the previous term by x^2 and dividing by (2*n)*(2*n-1).]
I get good results between 4 and 10 on this minor fix of your code:
#include <stdio.h>
#include <math.h>
double poww( float number, int a )
{
float result = 1.0;
int i;
for( i = 0; i < a; i++ )
{
result = result * number;
}
return result;
}
double factorial(int n)
{
switch (n)
{
case 0: return 1;
break;
default: return n * factorial(n-1);
}
}
int main(){
puts("Enter start: ");
float start;
scanf("%f", &start);
puts("\nEnter end: ");
float end;
scanf("%f", &end);
puts("\nSubintervals:");
int subinterval;
scanf("%d", &subinterval);
float h = (end - start) / (float)subinterval;
printf("h is : %3.2f \n", h);
double x, result, temp;
int n;
for( x = start; x <= end; x += h){
result = 0;
for(n = 0 ; ; n++){
temp = poww(x, 2 * n) / (factorial( 2 * n ) * 1.0);
if(temp < 0.00001){
break; }
else{
result = result + temp;
printf("X = %f temp = %f, result = %f\n", x, temp, result);
}
}
printf("X = %f, result = %3.2f, cosH = %3.2f\n\n", x, result, cosh(x) );
}
puts("Press any key...");
getchar();
return 0;
}

Related

Why don't float operations work properly?

I'm new to C, but i have previously coded in C++ and C#. I have written this code as an assignment, but the float operations don't work properly. What it's supposed to do is, by entering two positive integers, n and m, the end result should be this a sum of a sum with n and the square root of a multiplication.
My problem is that, even though the first sum works, both the multiplication and the square root (and in the end the final sum) don't work. In the end, whatever two numbers n and m i write, the sum will be ok and the other two will be completely innaccurate - either 1, both the multiplication and the final sum, or something that makes no sense (to be precise, "1.#INF00").
This is the code i have written. Does anybody know what i did wrong, or how can I fix this?
float sum(int n)
{
float s = 0;
for(float i = 1; i<=(float)n; i++)
{
s += (2*i)/(3*i*i+4);
}
return s;
}
float multiplication(int m)
{
float p = 1;
for(float j = 1; j <= (float)m; j++)
{
p *= (float)(j*j+1);
}
return p;
}
int main()
{
int n;
int m;
scanf("%i", &n);
scanf("%i", &m);
float s = sum(&n);
float p = multiplication(&m);
float e = s + (float)sqrt(p);
printf("The sum is %f \n", s);
printf("The multiplication is %f \n", p);
printf("The final expression is %f \n", e);
getch();
return 0;
}
You should pass the integer values, not pointers, to the functions sum and multiplication.
float sum(int n)
{
float s = 0;
for(float i = 1; i<=(float)n; i++)
{
s += (2*i)/(3*i*i+4);
}
return s;
}
float multiplication(int m)
{
float p = 1;
for(float j = 1; j <= (float)m; j++)
{
p *= (float)(j*j+1);
}
return p;
}
int main()
{
int n;
int m;
scanf("%i", &n);
scanf("%i", &m);
float s = sum(n); /* pass an integer, not a pointer */
float p = multiplication(m); /* pass an integer, not a pointer */
float e = s + (float)sqrt(p);
printf("The sum is %f \n", s);
printf("The multiplication is %f \n", p);
printf("The final expression is %f \n", e);
getch();
return 0;
}

C.find an error in a very small program.Calculating the sum of the first k numbers of the sequence

Calculating the sum of the first k numbers of the sequence a[0] = 1, a[k] = k*a[k-1] +1/k ( k = 1, 2, ... ).
UPD
There is still a problem with the recursive function ...What is the error?
#include <stdio.h>
#include <stdlib.h>
float m(float n){
float k=1;
float sum=k;
int i;
for (i=1; i<n;i++){
k = (i*k+1.0/i);
sum = sum+k;
}
return sum;
}
float Fn(float n)
{
if (n==0) {
return 1;}
return ((n*Fn(n-1)+1.0/n)+Fn(n-1));
}
int main(int argc, char *argv[]) {
float k;
printf("input k : ");
scanf("%f",&k);
printf("res %f \n",Fn(k));
return 0;
}
There were several issues in your code:
Integer division: 1/n = 0
There was a confusion between the term value Fn and the sum value
An iterative solution is simpler here than a recursive one
Here is a code, with both iterative and recursive implementations:
#include <stdio.h>
#include <stdlib.h>
float sum_fn(int n){
float Fk = 1;
float sum = Fk;
for (int i = 1; i <= n; i++){
Fk = i*Fk + 1.0/i;
sum += Fk;
}
return sum;
}
float sum_recursive(int n, float *sum){
if (n == 0) {
*sum += 1.0;
return 1.0;
}
float Fn = n * sum_recursive(n-1, sum) + 1.0/n;
*sum += Fn;
return Fn;
}
int main(int argc, char *argv[]) {
int k;
printf("input k : ");
scanf("%d", &k);
printf("k = %d\tsum = %f\n", k, sum_fn(k));
float sum = 0;
sum_recursive(k, &sum);
printf("k = %d\tsum = %f\n", k, sum);
return 0;
}

How to print this series x-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!) in C/C++?

I wish to write a program which calculates the series x-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!) by taking x and n as user inputs.
This is what i've tried, and well there's no output when I enter the values for x,n:
#include<stdio.h>
#include<math.h>
//#include<process.h>
#include<stdlib.h>
double series(int,int);
double factorial(int);
int main()
{
double x,n,res;
printf("This program will evaluate the following series:\nx-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)\n");
printf("\nPlease enter a value for x and an odd value for n\n");
scanf("%lf%lf",&x,&n);
/*if(n%2!=0)
{
printf("Please enter a positive value!\n");
exit(0);
}*/
res=series(x,n);
printf("For the values you've entered, the value of the series is:\n %lf",res);
}
double series(int s, int t)
{
int i,sign=1; double r,fact,exec;
for(i=1;i<=t;i+2)
{
exec=sign*(pow(s,i)/factorial(i));
r+=exec;
sign*=-1;
}
return r;
}
double factorial(int p)
{
double f=1.0;
while(p>0)
{
f*=p;
p--;
}
return f;
}
When I enter values for x and n, it simply shows nothing.
While I've written in C, C++ solutions are also appreciated.
Output window in code::blocks
The loop
for(i=1;i<=t;i+2)
in the function series() is an infinite loop when t >= 1 because i isn't updated in the loop. Try changing + to += and use
for(i=1;i<=t;i+=2)
instead. Also it seems you should use type int for x and n in the function main() because the arguments of series() is int. Don't forget to change the format specifier when changing their types.
Thanks to all those who helped. Here's the final working code:
#include<stdio.h>
#include<math.h>
#include<process.h>
#include<stdlib.h>
double series(int,int);
double factorial(int);
int main()
{
int x,n; double res;
printf("This program will evaluate the following series:\nx-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)\n");
printf("\nPlease enter a value for x and an odd value for n\n");
scanf("%d%d",&x,&n);
if(n%2==0)
{
n=n-1;
}
res=series(x,n);
printf("For the values you've entered, the value of the series is:\n%lf",res);
}
double series(int s, int t)
{
int i,sign=1; double r=0.0,fact,exec;
for(i=1;i<=t;i+=2)
{
exec=sign*(pow(s,i)/factorial(i));
r+=exec;
sign*=-1;
}
return r;
}
double factorial(int p)
{
double f=1;
while(p>0)
{
f*=p;
p--;
}
return f;
}
in loop we step by two for getting odd numbers.by multiplying the current temp variable by the previous temp variable in the loop with neccesary terms like x square and dividing by i*(i-1) i.e for factorial and multiply with -1 i.e to achive negavtive number alternatively. by using this temp variable and adding it to sum variable in every iteration will give us answer.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int n, x;
cout << "enter x and no.of terms: ";
cin >> x >> n;
float sum = 0, temp = x;
for (int i = 3; i < 2 * n + 2; i = i + 2)
{
temp = ((-1 * temp) *(x*x)) / i*(i-1);
sum = sum + temp;
}
cout << x + sum;
return 0;
}
// series x-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)
#include<stdio.h>
#include<math.h>
double factorial (int);
double calc (float, float);
int
main ()
{
int x, deg;
double fin;
printf ("x-(x^3/3!)+(x^5/5!)-(x^7/7!)+...(x^n/n!)\n");
printf ("Enter value of x\n");
scanf ("%d", &x);
printf ("highest degree in denom i.e., 1 or 3 or 5 whatever, it should be odd .\n");
scanf ("%d", &deg);
fin = calc (x, deg);
printf ("the summation of series =%1f\n", fin);
return 0;
}
double calc (float num, float res)
{
int count, sign = 1;
double rres = 0;
for (count = 1; count <= res; count += 2)
{
rres += sign * (pow (num, count) / factorial (count));
sign *= -1;
}
return (rres);
}
double factorial (int num)
{
int count;
double sum = 1;
for (count = 1; count <= num; count++)
{
sum *= count;
}
return (sum);
}

getting three errors

This code is showing following errors:
missing ) before type
calc: too few arguments to call
syntax error ) Visual stuio 2013 platform
MyCode:
#include "math.h"
void main()
{
float num[5];
float (calc (float num[5]));
calc(float num);/* transferring control to calc function)*/
getch();
}
float calc(float nun[5])
{
int i;
float num[5];
float sum, avg, sqmn1, sumsqmn = 0, sqsd = 0; float sd;
printf("\nEnter 5 numbers");
for (i = 0; i < 5; i = i + 1)
{
scanf("%f", &num[i]);
}
sum = 0;
for (i = 0; i < 5; i = i + 1)
{
sum = sum + num[i];
}
avg = sum / 5;
for (i = 0; i < 5; i = i + 1)
{
sqmn1 = (avg - num[i])*(avg - num[i]);
sumsqmn = sumsqmn + sqmn1;
}
sqsd = sumsqmn / 5;
sd = sqrt(sqsd);
printf("\nThe sum is %f", sum);
printf("\nThe average is %f", avg);
printf("\nThe stabdard deviation is %f", sd);
getch();
}
float (calc (float num[5]));
in your main(), what is this exactly?
IMO, it can be,
float ff;
ff = calc(num);
Other than that,
#include <stdio.h> is missing.
Forward declaration of float calc(float nun[5]) is missing.
You can rewite your main() as
int main()
{
float num[5];
float ff;
ff = calc(num);/* transferring control to calc function)*/
getch();
return 0;
}
but then also, you're passing num from main() to calc() but i see you never used it. What are you upto?

Custom Recursive function |returning no values at all| in C

I thought of making this An=8(An-1)*(An-1)/An-2 while a1=1,a0=1
With the following code for n=2 a2=0.0000 which is altogether wrong
On the other hand (Sum of An) S(n)=1+1+0.0000(false number) theoretically correct
#include <stdio.h>
float rec(int n);
float sum(int n);
main()
{
int n;
printf("\nInput N of term an: ");
scanf("%d",&n);
printf("\n\na%d=%f",n,rec(n));
printf("\n\nS(%d)=%f",n,sum(n));
}
float rec(int n)
{
int i;
float a[1000]={1,1};//a0=1,a1=1
if(n<0)
printf("\nNegative values of N are invalid");
else if(n==0)
return a[0];
else if(n==1)
return a[1];
else if(n>1)
for(i=2;i<=n;i++)
a[i]=((8 * a[i-1]*a[i-1]) - 1)/a[i-2];
return a[i];
}
float sum(int n)
{
int i;
float sum=0;
for(i=0;i<=n;i++)
sum+=rec(i);
return sum;
}
float a[1000]={1,1};
initializes a[0] = 1 and a[1] = 1 and rest of the elements to 0.
Now, you are returning a[i] from your function. For n=2 it will return a[3], which is 0 of course, but not the a[2] as you are expecting.
Now just change the return value to a[i-1] and it will work.
float rec(int n)
{
int i;
...
...
return a[i-1];
}
for(i=2;i<=n;i++)
a[i]=((8 * a[i-1]*a[i-1]) - 1)/a[i-2];
return a[i];
problem here, you will always get zero!!! why?
say i input 3,, now say i = 3,alls well a[3] gets calcualted, now you program goes back to the for loop, now i =4, it now does not fit the check i<=n, and so now i is 4,
you are returning a[i] which is actually a[myanswer+1]...
fix it by returning a[i-1]
At this point in rec:
return a[i];
i is 3, not 2, because it was incremented before the last test of the loop. As such you're returning the element of the array after the last one set. Be careful if you fix this by returning a[i-1] because if i is never initialized or is 0, this will cause a problem. You should clean up the rec method a bit to handle these corner cases, but the immediate problem is that i is 3, not 2.
Replace
return a[i];
with
return a[n];
(As an aside, you do not need the extra branches for 0 and 1.)
A beautiful example of Schlemiel the Painter's algorithm :)
About half the computations are done unnecessarily multiple times
The array is unnecessary and defeats the whole point of using a recursive approach
Beside, it is defined to hold 1000 values, but the function grows so fast that it will exceed a float capacity after 10 terms or so.
A more streamlined version here :
#include <stdio.h>
float A (int n, float * sum)
{
if (n <= 0) { *sum = 0; return 0; }
if (n == 1) { *sum = 1; return 1; }
if (n == 2) { *sum = 2; return 1; }
float anm2 = A(n-2, sum); // store A(n-2). sum will be overwritten by A(n-1)
float anm1 = A(n-1, sum); // store A(n-1) once to avoid calling A twice, and get preceding sum
float an = ((8 * anm1*anm1) - 1)/anm2;
*sum += an;
printf ("index %d : term %g sum %g\n", n, an, *sum);
return an;
}
int main (void)
{
int n;
float sum;
printf("\nInput N of term an: ");
scanf("%d",&n); printf("\n");
printf("\na%d=%f",n,A(n, &sum));
printf("\n\nS(%d)=%f",n,sum);
}
Beside, recursion is unnecessary and leads to inefficient and confusing code.
See a more straightforward solution here:
#include <stdio.h>
typedef struct {
float term;
float sum;
} A; // current term and sum of series A
void compute_A (int n, A * res)
{
int i;
float anm1, // a[n-1]
anm2; // a[n-2]
// special case for n<=1
if (n == 1)
{
res->sum = res->term = 1;
return;
}
if (n <= 0)
{
res->sum = res->term = 0;
return;
}
// initial terms
anm2 = anm1 = 1;
// initial sum
float sum = anm1+anm2;
// compute the remaining n-2 terms and cumulate the sum
for (i = 2 ; i <= n ; i++)
{
// curent term
float an = ((8 * anm1*anm1) - 1)/anm2;
// cumulate sum
sum += an;
// shift computation window
anm2 = anm1;
anm1 = an;
printf ("index %d : term %g sum %g\n", i, an, sum);
}
// report result
res->sum = sum;
res->term = anm1;
}
int main (void)
{
int n;
A res;
printf("\nInput N of term an: ");
scanf("%d",&n); printf("\n");
compute_A (n, &res);
printf("\na%d=%f",n,res.term);
printf("\n\nS(%d)=%f",n,res.sum);
}
float rec(int n){
static max_i = 1;
static float a[1000]={1,1};//a0=1,a1=1
int i;
if(n<0){
printf("\nNegative values of N are invalid");
return NAN;//<math.h>
}
if(n >= 1000){
printf("\nMore than 1000 are invalid");
return NAN;
}
if(n<2)
return a[n];
if(n>max_i){
for(i=max_i+1;i<=n;++i)
a[i]=((8 * a[i-1]*a[i-1]) - 1)/a[i-2];
max_i = n;
return a[n];
}
return a[n];
}

Resources