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);
}
Related
#include <stdio.h>
#include<math.h>
int series(float,float);
int main()
{
float x,n,series_value;
printf("Enter the value of x: ");
scanf("%f",&x);
printf("\nEnter the value of n: ");
scanf("%f",&n);
series_value=series(x,n);
printf("\nValue of series sin (%.2f) is: %f\n",x,series_value);
return 0;
}
int series(float x,float n)
{
int i,sum=0,sign=-1;
int j,fact=1,p=1;
for (i=1; i<=(2*n)-1; i+=2)
{
for (j=1; j<=i; j++)
{
p=p*x;
fact=fact*j;
}
sign=-1*sign;
sum=sum + sign*p/fact;
}
return (sum);
}
Output:
Enter the value of x: 5
Enter the value of n: 10
(lldb)
and this message
Thread 1: EXC_ARITHMETIC (code=EXC_I386_DIV, subcode=0x0)
![Thread 1 Queue : com.apple.main-thread (serial)
]1
Why is this message coming? and what is wrong in the program as answer is not coming right
There is a few problems with your code. As #PaulHankin said, when fact overflows and becoms zero, you will have a division by zero, and "weird things" happen.
Your factorial and power calculation is also wrong. You are recalculating it in each iteration of the outer loop without reseting fact and p first:
fact = 1; // You need to reset fact and p to its start value here
p = 1;
for (j=1; j<=i; j++)
{
p=p*x;
fact=fact*j;
}
Your third problem is that for your function calculate the correct value for sin, which is not an integer value, you need to use float, or even better double, when calculating sum. So sum must be declared float, and the division p/fact must use float division. By also declaring p and fact as float, you will solve both the overflow issue, and use the correct division. Naturally your function must also return a float
float series(float x,float n)
{
int i,sign=-1;
int j,
float sum = 0;
float fact = 1;
float p = 1;
for (i=1; i<=(2*n)-1; i+=2)
{
fact = 1;
p = 1;
for (j=1; j<=i; j++)
{
p=p*x;
fact=fact*j;
}
sign=-1*sign;
sum=sum + sign*p/fact;
}
return (sum);
}
This code still has a minor problem. By having an inner loop, it is slower than necessary. Since this probably is homework, I am not getting rid of that loop for you, just giving you a hint: You don't have to recalculate fact from scratch on each iteration of the outer loop, just try to find out how fact changes from one iteration to the next. The same goes for p.
//Series of Sinx
#include<stdio.h>
#include<math.h>
#define ACCURACY 0.0001
int factorial(int n);
int main()
{
float x,sum,term;
int i,power;
printf("Enter value of X: ");
scanf("%f",&x);
i=1;
power=3;
sum=x;
term=x;
while(term>=ACCURACY)
{
term = pow(x,power) / factorial(power);
if(i%2==1)
{
sum -= term;
}
else
{
sum += term;
}
power+=2;
i++;
}
printf("sin(%f) = %.6f\n",x,sum);
return 0;
}
int factorial(int n){
int i=n,fact=1;
for(i=1;i<=n;i++)
{
fact=fact*i;
}
return fact;
}
plenty bugs. To do not caclulate the fact values all the time they are in the lookup table
#include <stdio.h>
#include <math.h>
double series(double,int);
long long fact[] = { 1, 2, 6, 24,
120, 720, 5040, 40320,
362880, 3628800, 39916800, 479001600,
6227020800, 87178291200, };
double mypow(double x, unsigned p)
{
double result = x;
while(p && --p)
result *= x;
return result;
}
int main()
{
for(double x = 0; x <= M_PI + M_PI / 60; x += M_PI / 30)
printf("Value of series sin (%.2f) is: %f\n",x,series(x, 5));
fflush(stdout);
}
double series(double x,int n)
{
double sum = x;
int i,sign=1;
for (i=3; i<=(2*n)-1; i+=2)
{
sign=-1*sign;
sum += sign*(mypow(x, i)/fact[i -1]);
}
return (sum);
}
https://godbolt.org/z/U6dULN
maybe its due to floating-point exception as u have declared that the function should return int type value
int series(float,float);//hear
so u can try editing the return type of this function as float
Note:-also u need to change at function definition and the datatype of
int i,sum=0,sign=-1;
int j,fact=1,p=1;
to float as it is returning the value (sum) which should also be float
ERRRO CODE (advancedpower function)
When I operate this code and write the input, the output is wrong.
use : ln(x), e^x
consider when a == 0
x can be positive, negative, or zero or any fractional number
if a==0 -> a^x=0
a^x=advancedpower(ln(exp(power(a^x)))
#include <stdio.h>
#include <assert.h>
int factorial(int x)
{
if(x>0)
{
return (x*factorial(x-1));
}
if(x==0)
{
return 1;
}
else
return 0;
}
float power(float x, float y)
{
float r;
r=1.0;
if (x==0)
{
return 0;
}
if (y==0&& x!=0) {
return 1;
}
else
for(int i=1; i<=y;i++) {
r=r*x;
}
return r;
}
float exp(float x){
float sum=1.0;
for (int i = 0;i<10; i++) {
sum = sum + (power(x,i)/factorial(i));
}
return sum;
}
float ln(float x)
{
assert(x > 0);
float o= 1.0;
for (int i = 1;; i++) {
int k = 2*i-1;
float t = 2.0* power((x-1)/(x+1),k)/k;
o=o+t;
}
return o;
}
float advancedpower(float n1,float n2){
if (n1 ==0){
return 0;
}
else
return (exp(power(n1,n2)));
}
int main()
{
float a, x;
scanf("%f%f", &a, &x);
printf("%.4f", advancedpower(a, x));
return 0;
}
input 2.0 0.5
output 1.4142
however when I enter 2.0 0.5, the output is 3.7183
What should I have to change.....
With the input “2.0 0.5”, a is set to 2, and x is set to .5. Then advancedpower is called with arguments 2 and .5. In turn, advanceddpower calls power, also with arguments 2 and .5.
power is a recursive function. When x and y are not zero, it calls power(x, y - 1). This results in calling power with arguments 2 and −.5. Then it executes the same code again, which calls power with arguments 2 and −1.5. Then again with 2 and −2.5. This continues until the stack is exhausted, and the program crashes.
This code has not been written to handle these values. You need to rethink the design.
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).
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;
}
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.