Exponential function in C using recursion function - c

I am trying to CALCULATE the Exponential function of x with recursion function .the Exponential function is calculated from this equation .
I divided the Exponential function for two part the first part which is Fracture
(i calculated it with the recursion function at the bottom and then put this part in while loop at the main function to find the sum from 0 to N
AS i am beginner in c and my English is not perfect please explain my Mistake in a SIMPLE WAY .
THANK IN ADVANCE .....
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<math.h>
#include<conio.h>
double faktoriyel(double x,double N);
int main(){
double N, x, a;
double s = 0;
scanf("%lf", &x);
scanf("%lf", &N);
a = N;
do
{
s += faktoriyel(x, N);
--a;
}while (a > 0);
printf("\n%lf\n", s);
}
double faktoriyel(double x, double N)
{
if (N < 0)
return -1;
else if (N < 2)
return pow(x, N) / 1;
else
return (pow(x, N) / N * faktoriyel(x, N - 1));
}

Your base case is not right.
It should be
if(N == 0)
return 1;
Why because anything raised to the power 0 is one.So returning 0.
Your method is not proper way of using recursion.
Check this code.
#include <stdio.h>
int power(int n1, int n2);
int main()
{
int base, powerRaised, result;
`printf("Enter base number: ");`
`scanf("%d",&base);`
`printf("Enter power number(positive integer): ");`
`scanf("%d",&powerRaised);`
`result = power(base, powerRaised);`
`printf("%d^%d = %d", base, powerRaised, result);`
`return 0;`
}
int power(int base, int powerRaised)
{
if (powerRaised != 0)
`return (base*power(base, powerRaised-1));`
`else`
`return 1;`
}

I changed it a bit here:
double faktoriyel(double x,double N)
{
if (N == 0) return 1;
else return (x/N * faktoriyel(x,N-1));
}
why? because you wrote
return (pow(x, N) / N * faktoriyel(x, N - 1));
which results in caculating
(x^(N+(N-1)+.....+1))/(N!)
instead of x^N/N!.
that is because you recalculate x^N every call to the function
and then multiply it :
(x^N)(x^(N-1))....*1
and here:
do
{
s+=faktoriyel(x,N);
--N;
}while (N>=0);
instead of this:
do
{
s += faktoriyel(x, N);
--a;
}while (a > 0);
because you actually calculated
x^N/N! + x^N/N! +.....+x^N/N!
instead of :
x^N/N! + x^(N-1)/(N-1)! +.....+1;
decrementing 'a' does not decrement N, resulting
in an incorrect calculation of e^x.
it should work btw.

Related

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).

Evaluating Taylor series expansion of e^x in C

I am very new to C programming. Here, I have written a very simple C program to evaluate the Taylor series expansion of exponential function e^x, but I am getting error in my output, though the program gets compiled successfully.
#include <stdio.h>
int main()
{
double sum;
int x;
printf("Enter the value of x: ");
scanf("%d",&x);
sum=1+x+(x^2)/2+(x^3)/6+(x^4)/24+(x^5)/120+(x^6)/720;
printf("The value of e^%d is %.3lf",x,sum);
return 0;
}
^ in C is not an exponentiation operator. It is a bitwise operator. For a short number of terms, it is easier to just multiply.
You also need to take care of integer division. If you divide x*x/2, then you will get integer division. You need to divide the number to get a double answer, as shown below.
You can replace the line calculating the sum with the following line.
sum=1+x+(x*x)/2.0+(x*x*x)/6.0+(x*x*x*x)/24.0+(x*x*x*x*x)/120.0+(x*x*x*x*x*x)/720.0;
A better option would be to use a loop to calculate each term and add it to the answer.
double answer, term = 1;
int divisor = 1;
amswer = term;
for (i=0; i<6; i++)
{
term = term * x / divisor;
answer += term;
divisor *= (i+2);
}
Use pow() instead of ^
Use double x instead of int x
So the result code will look like:
#include <stdio.h>
#include <math.h>
int main()
{
double sum;
double x;
printf("Enter the value of x: ");
scanf("%lf",&x);
sum=1+x+pow(x,2)/2+pow(x,3)/6+pow(x,4)/24+pow(x,5)/120+pow(x,6)/720;
printf("The value of e^%f is %.3lf",x,sum);
return 0;
}
It should be linked with math lib, i.e.:
gcc prog.c -lm
As other people failed to provide proper piece of C code, I have to try it:
#include <stdio.h>
int main() {
printf("Enter the value of x: ");
double x;
scanf("%lf", &x);
double sum = 1.0 + x * (1.0 + x * (1.0 / 2 + x * (1.0 / 3 + x * (1.0 / 4 + x * (1.0 / 5 + x / 6.0)))));
printf("The value of e^%.3lf is %.3lf", x, sum);
}
Better make it dynamic like this one.
#include <stdio.h>
int power(int x,int n){
int sum=1,i;
if (n == 0)
return 1;
for(i=1; i<= n; i++){
sum *= x;
}
return sum;
}
int fact(int n){
if(n == 0)
return 1;
for(i=1; i<= n; i++){
fact *=i;
}
return fact;
}
int main()
{
float sum=0.0;
int i,x,n;
printf("Enter the value of x and n terms: ");
scanf("%d %d",&x,&n);
for(i=0; i<=n; i++){
sum += (float)power(x,i)/fact(i);
}
printf("The value of %d^%d is %.3f",x,n,sum);
return 0;
}

Factorial of a number using recursion without if - else & return statement in C

Everyone in the solutions are giving functions with if else statements and return statement which i don't want . I have clearly mentioned that there should be no if else and return statement . that's why in my program i also didn't use it
I want to know if we can write the factorial of a number using recursion without using any if-else statements and a return statement. If yes, then how?
I tried something like this:
int n;
int fact=1;
factorial(){
while(n){
fact= fact * n;
n--; factorial();
}
}
main(){
n = 5;
factorial();
printf("%d",fact);
}
The above program is correctly giving a factorial of the number but the recursive call is just a dummy here. The recursive call is not actually doing anything.
So is it possible to write a factorial of a number with recursion without return statement & ifelse where recursive calls are actually contributing to find the factorial
int result;
void factorial(int n)
{
(result = 1, n <= 1) || (factorial(n - 1), result *= n);
}
int main()
{
factorial(5);
printf("%d\n", result);
}
Or, better
void factorial(int *n)
{
int f;
(f = 1, *n <= 1) || (f = (*n)--, factorial(n), f *= *n);
*n = f;
}
int main()
{
int n = 5;
factorial(&n);
printf("%d\n", n);
}
Or, if ?: is allowed the last one can be rewritten without that || trickery
void factorial(int *n)
{
int s;
*n = *n <= 1 ? 1 : (s = (*n)--, factorial(n), *n * s);
}
I think you are using C in a wrong way, because to use the global variable n is wrong practice. It would have to be a parameter of the function factorial.
Once this issue is fixed, we can handle the problem you are asking for.
I see unnecessary to restrict ourselves to "not use" if-else sentences.
Anyway, it's easy to do it in C, since we have the ternary operator.
For example, the following:
char c = (3<4)? 'y': 'n';
is equivalent to:
char c;
if (3<4)
c = 'y';
else
c = 'n';
In the case of recursive factorial, we would have:
int factorial(int n) {
return (n <= 1)? 1: factorial(n-1);
}
Using a recursive helper function:
int helperfact(int *m, int *n){
*n>0 && ( *m *= (*n)--, helperfact(m, n));
}
void fact(int n){
int m = 1;
helperfact(&m,&n);
printf("%d\n",m);
}
int main(void){
fact(10);
fact(0);
return 0;
}
Output:
3628800
1
Your could try this:
int factorial (int t) /*t = factorial*/
{
int r; /*result*/
if (t == 1) /*if t = 1 the recursion will end*/
{
return 1;
}
r = t * factorial(t - 1) ; /*calling the function again with times - 1*/
return r; /*will make recursion until t = 1 */
}
Hope it works.

Recursive exponentiation

so I have to write a recursive algorithm for exponentiation and I have to use this to make the algorithm faster: and then I'd have to figure out how many time multiplication is happening. I wrote it, but I am not sure if I am right - also I need some help with figuring out the multiplication part.
#include <stdio.h>
#include <math.h>
double intpower(double x, int n)
{
double result;
if(n>1&&n%2!=0) {result=x*intpower(x,(n-1)/2)*intpower(x,(n-1)/2);}
if(n>1&&n%2==0) {result=intpower(x,n/2)*intpower(x,n/2);}
if(n==1) return x;
else return result;
}
int main()
{
int n;
double x,result;
printf("x\n");
scanf("%lf", &x);
printf("n\n");
scanf("%d", &n);
printf("result = %.2f\n", intpower(x,n));
return 0;
}
The inductive definitions are saying
If k is even, then x^k = [ x^(k/2) ] ^ 2
If k is odd, then x^k = x * [ x^(floor(k)/2) ] ^ 2
With these it's a bit easier to see how to arrange the recursion:
#include <stdio.h>
double int_pwr(double x, unsigned k)
{
if (k == 0) return 1;
if (k == 1) return x; // This line can be omitted.
double y = int_pwr(x, k/2);
return (k & 1) ? x * y * y : y * y;
}
int main(void)
{
double x;
unsigned k;
scanf("%lf%u", &x, &k);
printf("x^k=%lg\n", int_pwr(x, k));
return 0;
}
I've changed types to be a bit more logical and saved an exponential (in k) amount of work that the OP's solution does by making two recursive calls at each level.
As to the number of multiplications, it's pretty easy to see that if k's highest order bit is 2^p (i.e. at position p), then you'll need p multiplications for the repeated squarings. Another way of saying this is p = floor(log_2(k)). For example if k=4=2^2, you'll square the square to get the answer: 2 multiplications. Additionally you'll need q-1 more, where q is the number of 1's in k's binary rep. This is the number of times the check for "odd" will be true. I.e. if k = 5 (which has 2 bits that are 1's), you'll square the square and then multiply the result by x one more time. To summarize, the number of multiplications is p + q - 1 with p and q as defined above.
To figure out how many times multiplication is happening, you could count them in intpower().
static int count = 0;
double intpower(double x, int n) {
double result;
if(n>1&&n%2!=0) {result=x*intpower(x,(n-1)/2)*intpower(x,(n-1)/2); count += 2;}
if(n>1&&n%2==0) {result=intpower(x,n/2)*intpower(x,n/2); count++;}
if(n==1) return x;
else return result;
}
int main() {
int n;
double x,result;
printf("x\n");
scanf("%lf", &x);
printf("n\n");
scanf("%d", &n);
mcount = 0;
printf("result = %.2f\n", intpower(x,n));
printf("multiplcations = %d\n", mcount);
return 0;
}
Try this
double intpower(double x, int n)
{
if(n == 0) return 1;
if(n == 1) return x;
if(n%2!=0)
{
return x*intpower(x,(n-1));
}
else
{
x = intpower(x,n/2);
return x*x;
}
}
or you can reduce your function to one line
double intpower(double x, int n)
{
return n == 0 ? 1 : n%2 != 0 ? x*intpower( x, (n-1) ) : (x = intpower(x, n/2), x*x);
}

Is this recursive GCD function correct? [duplicate]

This question already has answers here:
Recursion in C. Making a non-recursive function a recursive one
(3 answers)
Closed 10 years ago.
Everything compiles and runs perfectly for my program. I had to write a recursive GCD function. I used two functions however, gcdRecursive and gcd. Can I condense this code into a single function so I do not need the gcd function within my code below? Or is my code correct as it is and the two functions are both needed.
void gcdRecursive(int *x, int *y, int i){
if (i >= 1) {
if (*x % i == 0 && *y % i == 0) {
printf("The GCD of %d and %d is %d", *x, *y, i);
}
else {
gcdRecursive(x, y, i - 1);
}
}
}
void gcd(int *x, int *y){
getValuesForGCD(x, y);
gcdRecursive(x, y, *x);
}
Yes it is correct but it is by far sub-optimal.
EDIT: try to use this:
if (x > y)
gcd(x,y) = gcd(y, x);
if (y % x == 0)
gcd(x, y) = x;
else
gcd(x, y) = gcd(x, y%x)
A more compact form could be
int getGcd(int num1, int num2)
{
int remainder;
if(num2 != 0)
remainder = (num1 % num2);
return ((num2 == 0) ? num1: getGcd(num2, remainder));
}

Resources