Calculating a Serie in C - c

This image is the task I should do:
Whatever I enter between -1 and 1, the outputs are always 1.0000 or 2.0000. How can I do solve this problem? Below I attached my code.
#include <stdio.h>
#include <math.h>
int main() {
int i;
float x;
float sum=0;
printf ("enter an x\n");
scanf ("%f",&x);
if ((x>-1)&&(x<1))
{
for (i=0;i<101;i++)
sum= sum + (pow(x,i));
}
printf ("result=%f",sum);
return 0;
}

if ((x>-1)&&(x<1))
With this case your code will work only if x is zero so try removing if statement and do mention what output you expect for given particular input, it will be bit more helpful to answer it.
Try this code:
#include <stdio.h>
#include <math.h>
int main() {
int i; float x;
float sum=0;
printf ("enter an x\n");
scanf ("%f",&x);
for (i=0 ;i<101; i++)
sum+= (pow(x,i));
printf ("result=%f",sum);
return 0;
}

Even upon using a type like double you haven't got enough numerical precision to sum all the powers up to 100.
Executing the following snippet, you'll notice that, while the correct (numerically speaking) result is evaluated, the loop stops way before the 100th iteration, typically at 16:
#include <stdio.h>
#include <math.h>
#include <float.h>
// Analytically calculates the limit for n -> inf of the series of powers
double sum_of_powers_limit(double x)
{
return 1.0 / (1.0 - x);
}
int main(void)
{
double x = 0.1;
const int N = 100;
double sum = 1.0;
for (int i = 1; i <= N; ++i)
{
double old_sum = sum;
sum = sum + pow(x,i);
if (old_sum == sum)
{
fprintf(stderr, "Numerical precision limit reached at i = %d\n", i);
break;
}
}
printf(" result = %.*e\n", DBL_DECIMAL_DIG, sum);
printf("expected = %.*e\n", DBL_DECIMAL_DIG, sum_of_powers_limit(x));
return 0;
}
Also note that a more efficient way to evaluate this kind of polynomials is the Horner's method:
// Evaluates the sum s(x) = 1 + x + x^2 + ... + x^n using Horner's method
// It stops when it cannot update the value anymore
double sum_of_powers(double x, int n)
{
double result = 1.0;
for (int i = 0; i < n; ++i)
{
double old_result = result;
result = 1.0 + x * result;
if (old_result == result)
{
fprintf(stderr, "Numerical precision limit reached at i = %d\n", i);
break;
}
}
return result;
}

Related

How to convert floating-point in for-loop to integer in C, for correct calculation

I'm trying to understand C better. In an exercise I had to find out what is wrong about the following code example.
#include <stdio.h>
int main() {
int count;
float sum;
float i;
sum = 0, count = 0;
for (i = 1000; i <= 1000.04; i += .01) {
sum += i;
count++;
}
printf("Sum: %f, Count: %d\n", sum, count);
return 0;
}
I found out that it's a bad idea to use floating-point in loops because it causes problems bsince it's not accurate. Next step is to rewrite the code, so it does the same thing but without using floating-point in the loop. I'm stuck on this task, I don't know how to replace i <= 1000.04. For i += .01 I guess I could replace it with i++ and divide it with 100 somewhere else.
Any ideas how to fix it properly?
#include <stdio.h>
int main() {
int count;
float sum;
int i;
sum = 0, count = 0;
for (i = 100000; i <= 100004; i++) {
sum += i;
count++;
}
printf("Sum: %f, Count: %d\n", sum/100, count);
return 0;
}

How do I do a summation in C without math.c?

Hello I need to create this summation and if you put the number 30000 the response should the number of pi, however it's not working here's the summation and here's the code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <limits.h>
#include <ctype.h>
#include <stdbool.h>
int main( void ){
int num, k;
double pi= 0;
printf("Digite o total de termos >=30000: ");
scanf("%d", &num);
if (num < 30000){
printf("Erro.");
}else {
for (k = 1; k<= num; k++){
if (k % 2 == 0){
pi = (double)(-1)/ (2*k -1);
}else{
pi = (double)(1)/ (2*k -1);
}
pi = pi * 4;
}
printf("O valor de pi e %f", pi);
}
return 0; }
Here is a general way to sum things up:
double sum(int from, int to, double (*f)(int)) {
double ret = 0.0;
for(int i=from; i<to; i++)
ret+=f(i);
return ret;
}
And then you can write this function:
double fun(int current) {
double sign = current %2 == 0 ? -1.0 : 1.0;
return sign / (2*current - 1)
}
Finally, call it like this:
double pi = sum(1, num, fun);
Do note that this is probably not a good way to go if you're a beginner student that is looking for a solution to some homework.
#include <stdio.h>
int main(void) {
double pi=0;
for(int k=1; k<=3000; ++k)
{
pi += (2.*(k%2)-1) / (2*k-1); // This line does a summation, and uses floating point math (Not Integer Math)
}
printf("Pi : %f\n", 4*pi);
return 0;
}

Why is my average not the correct answer? (C code program to find mean)

I am bashing my head because I cannot figure out why my C code keeps printing the wrong average of a set of n numbers!
This is my code below:
int main()
{
int i;
int n;
int sum = 0.0;
int lowest;
int highest;
float average;
int range;
int middle;
double median;
printf("\nEnter the amount of numbers you want?\n");
scanf("%d",&n);
int numbs[n];
int temp[n];
for(i = 0;i < n; i++)
{
printf("\nEnter a number from 0 to 15: ");
scanf("%d",&temp[i]);
}
while (temp[i] < 0 || temp[i] > 15) than 15
{
printf("This number is not from 0 to 15! Please re-enter another number: ");
scanf("%d",&temp[i]);
}
numbs[i] = temp[i];
sum += numbs[i];
}
int sortt = 0, j, x;
for (x = 1; x < n; x++) {
for (j = 0; j < n - x; j++) {
if (numbs[j] > numbs[j + 1]) {
sortt = numbs[j];
numbs[j] = numbs[j + 1];
numbs[j + 1] = sortt;
}
}
}
lowest = numbs[0];
highest = numbs[n-1];
middle = n/2;
if (n % 2)
{
median = numbs[middle];
}
else
{
median = (numbs[middle - 1] + numbs[middle]) / 2.0;
}
average = sum/n;
range = highest - lowest;
printf("\nSum: %d", sum);
printf("\nAverage: %.2f", average);
printf("\nMedian: %.2f", median);
printf("\nRange: %d\n", range);
return 0;
}
This is my input and output below. You can see that 8 divided by 3 is not 2, it is 2.67! I've tried using double and float.
Input & Output:
You need to correct the following line:
average = sum/n;
to
average = (float)sum/n;
You have to cast your return value into float. Think about it as a function with the following definition:
float divide(int x,int y){
return x/y; // returns an integer instead of float.
}
While this definition:
float divide(int x,int y){
return (float)x/y; // creates a temporary float variable and returns it immediately as the returned value of the function.
}
In addition, declaring int sum=0.0 is definitely going to show you a warning when compiling with -Wall. Try to follow warnings that you get from your compiler and fix all of them before you run your program.
8 divided by 3 is 2, remainder 2. 8 and 3 are integers, and when you divide two integers, you use integer division with integer rules.
Also, this line might be confusing you:
int sum = 0.0;
Since sum is an int, this just sets sum to zero.
And:
average = sum/n;
Since both sum and n are integers, this is integer division. What you do with a result does not affect how that result is computed -- C's rules are complex enough already.
/*Here see you can intake all values as float instead */
#include <stdio.h>
#include <stdlib.h>
void main()
{
float i,n,a,b,sum,ave;
printf("This is a program to calculate the average of 'n' numbers \n");
printf("Of How many numbers do you want to calculate average \n");
scanf("%f", &n);
printf("Enter the first number \n");
scanf("%f", &a);
sum = a;
for (i=1;i<n;i++)
{
printf("Enter another number \n");
scanf("%f", &b);
sum = sum + b;
}
ave = (sum/n);
printf("The average of the %f number is %f", n, ave);
getchar();
}

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);
}

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