Solving n! with C (equation error somewhere) - c

In my quest to learn C I've come across a task which is causing me a few problems. I need to make an equation for the approximate value of the formulae n!, which can be described as:
n! = n^n*e^(-n)*sqrt(2(2*n+1/3)*PI), however I simply cannot get my values to corrospond with the actual value. 5! = 120ish
I can get a value of some 148ish
Can't figure out where my code is wrong:
#include <stdio.h>
#include <math.h>
#define PI 3.14156
#define E_CONST 2.7828
int main ()
{
double num;
double calc, first, second, third, fourth;
printf("Give an int: ");
scanf("%lf", &num);
first = pow(num , num);
second = pow(E_CONST, -num);
third = (2 * num + 1/3);
fourth = sqrt(2*third*PI);
//calc = first * second * fourth;
calc = pow(num, num) * pow(E_CONST, -num) * sqrt(2*(2*num+(1/3))*PI);
printf("Input: %f", num);
printf("1: %.2f\n2: %.10f\n3: %.8f\n4: %.2f\n", first, second, third, fourth);
printf("\nInt was: %.2f\n\nApproximate number: %.5f", num, calc);
return 0;
}
Feel like i have tried everything. The code is a bit messy, but it's because I've scrambled so much with it now.

3.14156 is a bad value for PI: it's better to use 3.1416, or 3.14159, or 4 * atan(1), or, for POSIX implementations, M_PI.
2.7828 is a very bad value for e: it's better to use 2.7183, or exp(1), or, for POSIX implementations, M_E.
1/3 is integer division, the result is 0: it's better to use 1.0/3.
Also your approximation is incorrect. The correct approximation is
n^n * e^(-n) * sqrt((2*n+1/3)*PI)

It seems you fell into the integer division trap with 1/3, which has the value 0. You need to write this with floating point constants as 1.0 / 3.0.

You probably need to type 1.0/3.0 to get one third.

Related

Why is pow() function in C giving wrong answer when it is odd exponential of 10 in a loop? [duplicate]

This question already has answers here:
Why pow(10,5) = 9,999 in C++
(8 answers)
Closed 2 years ago.
#include <stdio.h>
#include <math.h>
int main()
{
int loop, place_value=0, c = 5;
for(loop = 0; loop < c; loop++)
{
place_value = 0;
place_value = pow(10, loop);
printf("%d \n", place_value);
}
return 0;
}
This code gives
10
99
1000
9999
Why is 99 and 9999 there in 3rd and 5th line instead of 100 and 10000 respectively?
When asking for power normally, it gives right answer.
#include <stdio.h>
#include <math.h>
int main()
{
printf ("%d", (int) pow (10,3 ));
return 0;
}
1000
pow is a difficult routine to implement, and not all implementations give good results. Roughly speaking, the core algorithm for pow(x, y) computes a logarithm from (a part of) x, multiplies it by y, and computes an exponential function on the product. Doing this in floating-point introduces rounding errors that are hard to control.
The result is that the computed result for pow(10, 4) may be something near 10,000 but slightly less or greater. If it is less, than converting it to an integer yields 9999.
When you use arguments hard-coded in source code, the compiler may compute the answer during compilation, possibly using a different algorithm. For example, when y is three, it may simply multiply the first argument by itself, as in x*x*x, rather than using the logarithm-exponent algorithm.
As for why the low result happens with the odd numbers you have tested, consider what happens when we multiply 5.45454545 by various powers of 10 and round to an integer. 5.45454545 rounds down to 5. 54.5454545 rounds up to 55. 545.454545 rounds down to 545. The rounding up or down is a consequence of what fraction happens to land beyond the decimal point. For your cases with pow(10, loop), the bits of the logarithm of 10 may just happen to give this pattern with the few odd numbers you tried.
pow(x, y) function translate more or less to exp(log(x) * y), which will give a result that is not quite the same as x ^ y.
In order to solve this issue you can round this:
round(pow(x, y))
The rule of thumb: never use floating point functions (especially such a complicated ones like pow or log) with integer numbers.
Simply implement integer pow
unsigned intpow(unsigned x)
{
unsigned result = 1;
while(x --) result *= 10;
return result;
}
it will be much faster or even (the fastest one)
int intpow1(unsigned x)
{
const static unsigned vals[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, /* ... */};
#if defined(CHECK_OVERFLOW)
if(x >= sizeof(vals)/ sizeof(vals[0])) return -1;
#endif
return vals[x];
}

How to disable the rounded off on C programming

I want to get 998 / 999 = 0.998, but I get 0.999.
Can you help me?
#include <stdio.h>
#include <math.h>
int main() {
float a,b,c;
float d,e,f;
scanf("%f", &a);
d= a / 999;
scanf("%f", &b);
e= b / 999;
scanf("%f", &c);
f= c / 999;
printf("%.3f...\n", d);
printf("%.3f...\n", e);
printf("%.3f...\n", f);
}
The result is 0.99899899... so rounding it to 3 decimals should yield 0.999 and your program does that correctly.
If your intention is to round down with 3 decimals, then you must tell the program to do that instead. For that, you can use the floor function included in the math library you're using:
floor(998.0/999.0*1000)/1000;
Notwithstanding the fact that 998 / 999 is 0.998999...9, if you want to truncate on the 3rd significant figure, then one way is to write, from C99 onwards
truncf(998.f / 999 * 1000) / 1000;
or
floorf(998.f / 999 * 1000) / 1000;
You might find that the second way is more likely to be available pre-C99, if not then use say (long) in place of floorf, and replace the final division with 1000.f.
These can introduce joke digits from about the 7th significant figure, but the formatting choice you already use will obviate that.

From a float to an integer

Given this code that my professor gave us in an exam which means we cannot modify the code nor use function from other libraries (except stdio.h):
float x;
(suppose x NOT having an integer part)
while (CONDITION){
x = x*10
}
I have to find the condition that makes sure that x has no valid number to the right of decimal point not giving attention to the problems of precision of a float number (After the decimal point we have to have only zeros). I tried this condition:
while ((fmod((x*10),10))){
X = X*10
}
printf(" %f ",x);
example:
INPUT x=0.456; --------> OUTPUT: 456.000
INPUT X=0.4567;--------> OUTPUT; 4567.000
It is important to be sure that after the decimal point we don't have any
significant number
But I had to include math.h library BUT my professor doesn't allow us to use it in this specific case (I'm not even allowed to use (long) since we never seen it in class).
So what is the condition that solve the problem properly without this library?
As pointed out here previously:Due to the accuracy of floats this is not really possible but I think your Prof wants to get something like
while (x - (int)x != 0 )
or
while (x - (int)x >= 0.00000001 )
You can get rid of the zeroes by using the g modifier instead of f:
printf(" %g \n",x);
There is fuzziness ("not giving attention to the problems of precision of a float number") in the question, yet I think a sought answer is below, assign x to an integer type until x no longer has a fractional part.
Success of this method depends on INT_MIN <= x <= INT_MAX. This is expected when the number of bits in the significant of float does not exceed the value bits of int. Although this is common, it is not specified by C. As an alternative, code could with a wider integer type like long long with a far less chance of the range restriction issue.
Given the rounding introduced with *10, this method is not a good foundation of float to text conversion.
float Dipok(float x) {
int i;
while ((i=x) != x) {
x = x*10;
}
return x;
}
#include <assert.h>
#include <stdio.h>
#include <float.h>
void Dipok_test(float x) {
// suppose x NOT having an integer part
assert(x > -1.0 && x < 1.0);
float y = Dipok(x);
printf("x:%.*f y:%.f\n", FLT_DECIMAL_DIG, x, y);
}
int main(void) {
Dipok_test(0.456);
Dipok_test(0.4567);
return 0;
}
Output
x:0.456000000 y:456
x:0.456699997 y:4567
As already pointed out by 2501, this is just not possible.
Floats are not accurate. Depending on your platform, the float value for 0.001 is represented as something like 0.0010000001 in fact.
What would you expect the code to calculate: 10000001 or 1?
Any solution will work for some values only.
I try to answer to my exam question please if I say something wrong correct me!
It is not possible to find a proper condition that makes sure that there are no valid number after the decimal point. For example : We want to know the result of 0.4*20 which is 8.000 BUT due to imprecision problems the output will be different:
f=0.4;
for(i=1;i<20;i++)
f=f+0.4;
printf("The number f=0.4*20 is ");
if(f!=8.0) {printf(" not ");}
printf(" %f ",8.0);
printf("The real answer is f=0.4*20= %f",f);
Our OUTPUT will be:
The number f=0.4*20 is not 8.000000
The real answer is f=0.4*20= 8.000001

To print the answer from the series -> x^3 - x^5 + x^7 - x^9 +

#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int x,n;
float sum=0;
printf("Length and Value");
scanf("%d%d",&n,&x);
for(int i=1;i<=n;i++)
{
sum+=(pow(x,2*i+1) * pow(-1,i+1));
}
printf("%f",sum);
return 0;
}
I'm trying to solve this series in C language. Am I doing something wrong in the above code?
Yes, you're a bit wrong. In your code
printf("%f",sum);
sum is an int and using %f to print the value of an int is undefined behaviour.
The function pow() returns a double. You may want to change your sum to type double.
If you don't mind using your own version, a better looking implementation, without using pow() will be
Store the existing value.
Multiply by x * x on each iteration
Take care of -ve sign for even numbered iteration.
First things first, your printf has the wrong format specifier for an int: use %d instead. But for non-integral x, you'll want to refactor to a double anyway, so %f will probably be retained.
Secondly, don't use pow: it will not be precise (probably implemented as exp(log)) and you don't need to evaluate the power from scratch for each term.
Keep a running power: i.e. compute x * x * x initially, then successively multiply that by x * x for subsequent terms. Don't forget to alternate the signs: you can do that by multiplying by -1.
you are trying to find x^3,x^5 that is power in odd. so do a little change in your for loop. write this instead of your code. and if you give a large x or n value then it is preferable to declare sum as a long data type
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int x,n;
long sum=0;
printf("Length and Value");
scanf("%d%d",&n,&x);
for(int i=2;i<=n;i+=2)
{
sum+=(pow(x,i+1) * pow(-1,i));
}
printf("%l",sum);
return 0;
}
First of all, you are trying to evaluate a series that diverges for all points outside and on the circle of radius one (as a complex series). If you use an int for x, you will get each time values bigger and bigger, oscillating around 0. Try it with numbers of ||x|| < 1 (this means double or float for x)
All the other answers posted are also usefull to get sooner to the expected value.

Why does this integer division yield 0?

Could someone tell me why the following code is outputting 0 at the marked line?
It seems as if everything is correct but then when I try to get the result near the end it's giving me 0 each time.
#include <stdio.h>
int main() {
// Gather time-lapse variables
int frameRate, totalLengthSecs;
printf("How many frames per second: ");
scanf("%i", &frameRate);
printf("--> %i frames confirmed.", frameRate);
printf("\nDesired length of time-lapse [secs]: ");
scanf("%i", &totalLengthSecs);
printf("--> %i seconds confirmed.", totalLengthSecs);
int totalFrames = frameRate * totalLengthSecs;
printf("\nYou need %i frames.", totalFrames);
// Time-lapse interval calculation
int timeLapseInterval = totalLengthSecs / totalFrames;
printf("\n\n%i", timeLapseInterval); // <-- this prints 0
return 0;
}
In short: Integer division truncates
You need the following:
double timeLapseInterval = (double) totalLengthSecs / (double)totalFrames;
printf("\ntimeLapseInterval : %f \n", timeLapseInterval);
You are performing integer math.
Math between two integers will produce an integer. And the result will be rounded towards zero.
This line:
totalLengthSecs / totalFrames;
Is likely producing a result that's between 0 and 1. And getting rounded to 0
You are printing integers and therefore it will round down the value.
timeLapseInterval / totalFrames will be (1 / frameRate) which will be < 1 unless frameRate is 1 (or 0 in which case you have an error dividing by 0)
When you divide 2 numbers in C and the denominator is integer, the compiler intends it as an integer division. Therefore, if you divide 1 divided 2, it returns zero and not 0.5
Moreover, your output variable is an integer too, hence, if you expect decimal outputs, you won't get it.
You can fix it by doing:
float timeLapseInterval = totalLengthSecs / (float)totalFrames;
printf("\n\n%f", timeLapseInterval);
I hope this helps

Resources