I am trying to make a program in C that uses a recursive function to calculate the factorial for Euler's number, and sends that data to main where the recursive function is to stop once two successive values have a difference of 0.0000001, however i cannot seem to get my program to work as it keeps returning -inf. Anyone know what im doing wrong?
EDIT: With this current code i can get the program to print result as 0.5, but it does not increment n past 2.
#include <stdio.h>
double factorial(double n);
int main ()
{
double n;
double sum = 0;
double last;
double result = 0;
for (n = 1; result <=0.0000001; n++)
{
last = sum;
sum = factorial(n);
result = (1 / last) - (1 / sum);
printf("result is %lf\n", result);
}
printf("result is %lf\n", result); // troubleshooting
return 0;
}
double factorial(double n)
{
if (n > 0)
return ( n * factorial(n-1));
else
return 1;
}
On the first iteration in main:
sum == 0
last = sum; => last == 0
result = (1 / sum) - (1 / last); => 1 / last == 1 / 0 == inf
Then you subtract (1 / last), which is inf, from (1 / sum), and get negative infinity.
Also, the loop never iterates more than once because you return result on the very first iteration.
Related
One of my C assignments was it to write an approximation of arctan(x) in the language C. The equation which I should base it on is
arctan(x)=\sum {k=0}^{\infty }(-1)^{k} \tfrac{x^{2k+1}}{2k+1}
In addition x is only defined as -1<=x<=1.
Here is my code.
#include <stdio.h>
#include <math.h>
double main(void) {
double x=1;
double k;
double sum;
double sum_old;
int count;
double pw(double y, double n) {
double i;
double number = 1;
for (i = 0; i < n; i++) {
number *= y;
}
return(number);
}
double fc (double y) {
double i;
double number = 1;
for (i = 1; i <= y; i++){
number *= i;
}
return(number);
}
if(x >= (-1) && x <= 1) {
for(k=0; sum!=sum_old; k++) {
sum_old = sum;
sum += pw((-1), k) * pw(x, (2*k) + 1)/((2*k) + 1);
count++;
printf("%d || %.17lf\n", count, sum);
}
printf("My result is: %.17lf\n",sum);
printf("atan(%f) is: %.17f\n", x, atan(x));
printf("My result minus atan(x) = %.17lf\n", sum - atan(x));
} else {
printf("x is not defined. Please choose an x in the intervall [-1, 1]\n");
}
return 0;
}
It seemingly works fine with every value, except value 1 and -1. If x=1, then the output ends with:
...
7207 || 0.78543285189457468
7208 || 0.78536
Whereas the output should look more like this. In this case x=0.5.
25 || 0.46364760900080587
26 || 0.46364760900080587
My result is: 0.46364760900080587
atan(0.500000) is: 0.46364760900080609
My result minus atan(x) atan(x) = -0.00000000000000022
How can I improve my code so that it can run with x=1 and x=-1.
Thanks in advance.
PS: I use my own created pw() function instead of pow(), because I wanted to bybass the restriction of not using pow() as we didn't had that in our lectures yet.
PPS: I'd appreciate any advice as to how to improve my code.
In each iteration, you add (-1)k • x2k+1 / (2k+1), and you stop when there is no change to the sum.
If this were calculated with ideal arithmetic (exact, infinitely precise arithmetic), it would never stop for non-zero x, since you are always changing the sum. When calculating with fixed-precision arithmetic, it stops when the term is so small it does not change the sum because of the limited precision.
When |x| is less than one by any significant amount, this comes quickly because x2k+1 gets smaller. When |x| is one, the term becomes just 1 / (2k+1), which gets smaller very slowly. Not until k is around 253 would the sum stop changing.
You might consider changing your stopping condition to be when sum has not changed from sum_old very much rather than when it has not changed at all.
if(x >= (-1) && x <= 1) {
for(k=0; sum!=sum_old; k++) {
sum_old = sum;
sum += pw((-1), k) * pw(x, (2*k) + 1)/((2*k) + 1);
count++;
printf("%d || %.17lf\n", count, sum);
}
Comparing doubles can be tricky. The conventional way to compare doubles is to test within epsilon. There should be an epsilon value defined somewhere, but for your purposes how many digits are enough to approximate? If you only need like 3 or 4 digits you can instead have
#define EPSILON 0.0001 //make this however precise you need to approximate.
if(x >= (-1) && x <= 1) {
for(k=0; fabs(sum - sum_old) > EPSILON; k++) {
sum_old = sum;
sum += pw((-1), k) * pw(x, (2*k) + 1)/((2*k) + 1);
count++;
printf("%d || %.17lf\n", count, sum);
}
If the issue is that -1,1 iterate too many times either reduce the precision or increase the step per iteration. I am not sure that is what you're asking though, please clarify.
I think the cause of this is for a mathematical reason rather than a programming one.
Away from the little mistakes and adjustments that you should do to your code, putting x = 1 in the infinite series of arctan, is a boundary condition:
In this series, we add a negative value to a positive value then a negative value. This means the sum will be increasing, decreasing, increasing, ... and this will make some difference each iteration. This difference will be smaller until the preciseness of double won't catch it, so the program will stop and give us the value.
But in the sum equation. When we set z = 1 and n goes from 0 to ∞, this will make this term (-1^n) equal to 1 in one time and -1 in the next iteration. Also,
the value of the z-term will be one and the denominator value when n approaches infinity will = ∞ .
So the sum several iterations will be like +1/∞ -1/∞ +1/∞ -1/∞ ... (where ∞ here represents a big number). That way the series will not reach a specific number. This is because z = 1 is a boundary in this equation. And that is causing infinite iterations in your solution without reaching a number.
If you need to calculate arctan(1) I think you should use this formula:
All formulas are from this Wikipedia article.
Here is some modifications that make your code more compact and has less errors:
#include <stdio.h>
#include <math.h>
#define x 0.5 //here x is much easier to change
double pw(double, double); //declaration of the function should be done
int main() { //the default return type of main is int.
double k;
double sum = 0 ; //you should initiate your variables.
double sum_old = 1 ; //=1 only to pass the for condition first time.
//you don't need to define counter here
if(x < -1 || x > 1){
printf("x is not defined. Please choose an x in the interval [-1, 1]\n");
return 0;
}
for(k=0; sum!=sum_old; k++) {
sum_old = sum;
sum += pw((-1), k) * pw(x, (2*k) + 1)/((2*k) + 1);
printf("%.0f || %.17lf\n", k, sum);
}
printf("My result is: %.17lf\n",sum);
printf("atan(%f) is: %.17f\n", x, atan(x));
printf("My result minus atan(x) = %.17lf\n", sum - atan(x));
return 0;
}
double pw(double y, double n) { //functions should be declared out of the main function
double i;
double number = 1;
for (i = 0; i < n; i++) {
number *= y;
}
return(number);
}
double fc (double y) {
double i;
double number = 1;
for (i = 1; i <= y; i++){
number *= i;
}
return(number);
}
I am trying to generate all the Armstrong number from 0 to 999. I can't understand why my code doesn't work if I remove the sum=0; statement at the bottom of the program (line 22).
#include<stdio.h>
#include<conio.h>
int main()
{
int i, n=999, rem, num, sum=0;
for(i=0; i<n; i++)
{
num=i;
while(num != 0)
{
rem = num%10;
num = num/10;
sum = sum+(rem*rem*rem);
}
if (sum == i)
{
printf("%d\n", sum);
}
sum=0;
}
return 0;
}
You're just resetting the sum so that each iteration of the for loop has a fresh, zeroed sum.
If you don't do this, each iteration of the loop will keep sum as whatever value it was from the prior iteration, thus compounding the summation and giving incorrect values!
As mentioned in the comments, it's traditionally easier to understand if this is done at the beginning of the loop, and in conjunction with that, it's better still to keep variable scopes as narrow as possible, e.g.:
#include <stdio.h>
int main()
{
for(int i = 0; i < 999; i++)
{
int sum = 0;
int num = i;
while(num != 0)
{
int rem = num % 10;
num = num / 10;
sum = sum + (rem * rem * rem);
}
if (sum == i)
{
printf("%d\n", sum);
}
}
return 0;
}
In the for loop, the first usage of sum is sum = sum + (rem*rem*rem);, so if you do not want to use the value of the sum from the previous iteration, you have to reset its value to zero at the beginning of each iteration of the for loop. In your code, you reset its value to zero just before the for loop, and at the end of each iteration (line 22), which does the trick.
An Armstrong number N is where the sum of the individual digits (say, A, B, C), raised to the power of the number of digits, equals the number itself.
N = A^3 + B^3 + C^3
So to calculate this for 0-999, you need a loop. In each iteration of the loop you need to start the summation over again from 0. Take i=10 and i=11 from your loop as an example. Neither is an Armstrong number, but they should be:
i=10: 1^2 + 0^2 = 1
i=11: 1^2 + 1^2 = 2
Without resetting sum, you're using the results of the previous numbers calculation:
i=10: 1^2 + 0^2 + 9^1 (+ 8^1 + 7^1 + ...) ≠ 1
i=11: 1^2 + 1^2 + (1^2 + 0^2 + 9^1) + ... ≠ 2
I am getting negative and positive result : when I enter(n value odd) odd term produces even or and even term produces odd value. I have already made function for factorial it works fine.
#include <stdio.h>
#include <math.h>
#define PI 3.14159f
int factorial(int n);
float sine(float , int);
int i;
void main(){
float degree;
float radian;
float result;
int n;
printf("Enter the angle in degree: ");
scanf("%f",°ree);
printf("Enter the iteration: ");
scanf("%d",&n);
radian = degree * PI / 180;
result = sine(radian,n);
printf("%d",factorial(n));
printf("\n");
printf("sin%.2f = %.3f",degree,result);
}
int factorial(int n)
{
if(n==0)
return 1;
else if (n==1)
return 1;
else
return (n*factorial(n-1));
}
float sine(float an, int n)
{
if (an==0)
return 0;
else if(n>=0)
if(n%2==1)
return (sine(an,n-2) - pow(an,n)/factorial(n)) * pow(-1,n);
else
return (sine(an,2*n-1) - pow(an,2*n+1)/factorial(2*n+1)) *-1 ;
}
float sine(float an, int n)
{
if (an == 0)
return 0;
The above condition returns 0 for sin(0) so it is of no use in rest of the recursion and it works fine.
else if(n >= 0)
if(n%2 == 1)
return (sine(an,n-2) - pow(an,n)/factorial(n)) * pow(-1,n);
else
return (sine(an,2*n-1) - pow(an,2*n+1)/factorial(2*n+1)) *-1 ;
Lets see where this part of your function goes, by substituting the value of n:
Suppose we are start with degree = 30 and number of iterations = 3
Then:
n = 3;
n is odd so function returns:
((sine(an, 3-2) - (float)pow(an, 3) / factorial(3)) * -1);
n = 1;
n is again odd so function returns:
((sine(an, 1-2) - (float)pow(an, 1) / factorial(1)) * -1);
n = -1;
This time n < 0 so if-else conditions are skipped and some garbage value is returned because you did not tell your program what to return at n = 0
So you need your sine-function to return a default value when n = 0
pow(-1,n) will always return -1 for odd values of n, and 1 for even values of n. So the sign of output of sine() function is not changing alternately like in the series.
Answering to the comment: Why the sign seems to change for odd or even,
In your code values of n are skipping the even numbers, instead of decreasing n by 1 per call, you are passing only odd numbers.
return (sine(an,n-2) - pow(an,n)/factorial(n)) * pow(-1,n);
so what you get in the end is a sum of negatives; And when you start with a even value of n like 2, then sine() is called with odd value of n the second time which is (2*n-1) which again returns a sum of negatives.
Heres what you can do:
float sine(float an, int n)
{
if (an == 0 || n == 0)
return 0; //to end the recursion when number of iterations are finished
else
return -1*pow(-1,n)*pow(an,2*n-1)/factorial(2*n-1) + sine(an, n - 1);
}
// `-1*pow(-1,n)` returns a negative term for even value of n, and postive term for odd value of n as required. You dont need separate if-else for that
I am new to recursion so I am trying to write a simple program that adds to the nth number of the series 1/n. So if the user enters n = 4, the program will add 1 + 1/2 + 1/3 + 1/4. My program keeps outputting that the sum of the series is 0. Can someone please explain what I am doing wrong? I'd appreciate the help. Here is my code:
#include <stdio.h>
double sum(double n);
int main() {
double n;
double total;
printf("Enter a positive integer greater than 0: ");
scanf("%lf", &n);
total = sum(n);
printf("Sum: %lf", total);
return 0;
}
double sum(double n) {
if (n == 1)
return 1;
else
return ((1 / n) + sum(n - 1));
}
The problem is in the definition of this function:
double sum(int n) {
if (n == 1)
return 1;
else
return ((1 / n) + sum(n - 1));
}
n is int so 1/n will be always evaluated as int since both 1 and n are integers. Thus 1/n is always 0 for each n>1.
The solution would be to define n as double :
double sum(double n) {
if (n <= 1.0)
return 1.0;
else
return ((1.0 / n) + sum(n - 1.0));
}
Check your base case. sum(1) should return 1.
Also, an int divided by an int returns an int. Use a floating point number in your division.
It should be
double sum(double n) {
if (n == 1)
return 1.0;
else
return ((1.0 / n) + sum(n - 1));
}
1/n will always return 0 since 'n' acts as an integer value and not a float value even though the datatype is double as the value assigned to it is of type integer.
I created this function CalculateCos:
int Factorial (long int n)
{
long int r = 1;
for (int i = 2; i<=n; i++)
{
r = r*i;
}
return r;
}
float CalculateVariable(int CVnumber, int CVloopCounter)
{
float CVresult = 0;
CVresult = pow(CVnumber, (CVloopCounter*2)) / (long int)Factorial(CVnumber*2);
return CVresult;
}
float CalculateCos(int number)
{
float result = 1;
int loopCounter = 1;
int minusOrPlus = 1;
while(loopCounter <= precision && loopCounter <= 8)
{
if(!minusOrPlus)
{
result = result - CalculateVariable(number, loopCounter);
printf("%f\n", result);
minusOrPlus = 1;
}
else
{
result = result + CalculateVariable(number, loopCounter);
printf("%f\n", result);
minusOrPlus = 0;
}
loopCounter++;
}
return result;
}
The reason why I printf after the subtraction or adding, is because it gives me strange output, like:
Enter a number, for the cos function
6
1.000000
0.999997
1.000095
0.996588
1.122822
-3.421593
160.177368
-5729.385254
Result is: -5729.3852539
Official function result is: 0.9601703
Can you help me to get correct results on this?
UPDATE:
Now my solution is:
float CalculateCos(float number)
{
float result = 0;
float step = 1;
int loopCounter = 1;
while(loopCounter <= 5)
{
step = step * (-number) * number / (((2*loopCounter)-1)*((2*loopCounter)-2));
result += step;
loopCounter++;
}
return result;
}
Current problem:
since your Factorial function returns int and you casts it to long int, its result is going to overflow even before the input goes to 16 in your case (14! > max_int).
You're calculating cos using Taylor series:
cos(x) = 1 - x2/2! + x4/4! - x6/6!
+ ...
I'm not going to write code. But there are some things wrong in your program, which can be fixed easily:
The input is in radian, so number should be a float.
Calculating each step of Taylor series using exponentiation and factorial separately leads to overflow very soon. The correct way is maintaining a float variable: step = 1 at first and in kth loop iteration step = step * (- x) * x / ((2*k-1)*(2*k)). In this way, you simply add step to result in the loop and don't need minusOrPlus anymore.
The number of loop iterations is bounded by 8 which is too small, so the result could be not precise enough.
I don't see you use precision variable anywhere. It could be used to check precision of the result. For example, when abs(step) < precision, we're going to terminate the loop.