Why Is This Factorial Algorithm Not Accurate - c

Sorry I feel stupid asking this and am prepared to lose half of my points asking this but why does this algorithm not work? It works up to a point. After the number 13 the factorials are a little off. For instance the numbers do not entirely match in the hundreds thousands place and onward.
#include <stdio.h>
float factorial(unsigned int i) {
if (i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 13;
printf("Factorial of %d is %f\n", i, factorial(i));
return 0;
}
Here's the output:
Factorial of 13 is 6227020800.000000
Here is an example of inaccurate output:
Factorial of 14 is 87178289152.000000
The output for the number 14 should actually be this (from mathisfun.com)
14 87,178,291,200
I changed the return type to float to obtain more accurate output but I obtained this code for the most part from here: https://www.tutorialspoint.com/cprogramming/c_recursion.htm
EDIT: If I change to the return type to double the output is accurate up to 21.I am using the %Lf string formatter for the output in the printf function.

Simple. float cannot accurately store integers above 16777216 without loss of precision.
int is better than float. But try long long so you can properly store 19 digits.

OP is encountering the precision limits of float. For typical float, whole number values above 16777216.0f are not all exactly representable. Some factorial results above this point are exactly representable.
Let us try this with different types.
At 11!, the float results exceeds 16777216.0f and is exactly correct.
At 14!, the float result is imprecise because of limited precision.
At 23!, the double result is imprecise because of limited precision.
At 22!, the answer exceeds my uintmax_t range. (64-bit)
At 35!, the answer exceeds my float range.
At 171!, the answer exceeds my double range.
A string representation is accurate endlessly until it reaches buffer limitations.
#include <stdint.h>
#include <string.h>
#include <stdio.h>
uintmax_t factorial_uintmax(unsigned int i) {
if (i <= 1) {
return 1;
}
return i * factorial_uintmax(i - 1);
}
float factorial_float(unsigned int i) {
if (i <= 1) {
return 1;
}
return i * factorial_float(i - 1);
}
double factorial_double(unsigned int i) {
if (i <= 1) {
return 1;
}
return i * factorial_double(i - 1);
}
char * string_mult(char *y, unsigned base, unsigned x) {
size_t len = strlen(y);
unsigned acc = 0;
size_t i = len;
while (i > 0) {
i--;
acc += (y[i] - '0') * x;
y[i] = acc % base + '0';
acc /= base;
}
while (acc) {
memmove(&y[1], &y[0], ++len);
y[0] = acc % base + '0';
acc /= base;
}
return y;
}
char *factorial_string(char *dest, unsigned int i) {
strcpy(dest, "1");
for (unsigned m = 2; m <= i; m++) {
string_mult(dest, 10, m);
}
return dest;
}
void factorial_test(unsigned int i) {
uintmax_t u = factorial_uintmax(i);
float f = factorial_float(i);
double d = factorial_double(i);
char s[2000];
factorial_string(s, i);
printf("factorial of %3d is uintmax_t: %ju\n", i, u);
printf(" float: %.0f %s\n", f, "*" + (1.0 * f == u));
printf(" double: %.0f %s\n", d, "*" + (d == u));
printf(" string: %s\n", s);
}
int main(void) {
for (unsigned i = 11; i < 172; i++)
factorial_test(i);
return 0;
}
Output
factorial of 11 is uintmax_t: 39916800
float: 39916800
double: 39916800
string: 39916800
factorial of 12 is uintmax_t: 479001600
float: 479001600
double: 479001600
string: 479001600
factorial of 13 is uintmax_t: 6227020800
float: 6227020800
double: 6227020800
string: 6227020800
factorial of 14 is uintmax_t: 87178291200
float: 87178289152 *
double: 87178291200
string: 87178291200
factorial of 20 is uintmax_t: 2432902008176640000
float: 2432902023163674624 *
double: 2432902008176640000
string: 2432902008176640000
factorial of 21 is uintmax_t: 14197454024290336768
float: 51090940837169725440 *
double: 51090942171709440000 *
string: 51090942171709440000
factorial of 22 is uintmax_t: 17196083355034583040
float: 1124000724806013026304 *
double: 1124000727777607680000 *
string: 1124000727777607680000
factorial of 23 is uintmax_t: 8128291617894825984
float: 25852017444594485559296 *
double: 25852016738884978212864 *
string: 25852016738884976640000
factorial of 34 is uintmax_t: 4926277576697053184
float: 295232822996533287161359432338880069632 *
double: 295232799039604119555149671006000381952 *
string: 295232799039604140847618609643520000000
factorial of 35 is uintmax_t: 6399018521010896896
float: inf *
double: 10333147966386144222209170348167175077888 *
string: 10333147966386144929666651337523200000000
factorial of 170 is uintmax_t: 0
float: inf *
double: 72574156153079940453996357155895914678961840000000... *
string: 72574156153079989673967282111292631147169916812964...
factorial of 171 is uintmax_t: 0
float: inf *
double: inf *
string: 12410180702176678234248405241031039926166055775016...

Someone posted a similar question a while back. The consensus was if you're writing it for work use a big number library (like GMP) and if it's a programming exercise write up a solution using a character array.
For example:
/* fact50.c
calculate a table of factorials from 0! to 50! by keeping a running sum of character digits
*/
#include <stdio.h>
#include <string.h>
int main (void)
{
printf ("\n Table of Factorials\n\n");
// length of arrays = 65 character digits
char str[] =
"00000000000000000000000000000000000000000000000000000000000000000";
char sum[] =
"00000000000000000000000000000000000000000000000000000000000000001";
const int len = strlen (str);
int index;
for ( int i = 0; i <= 50; ++i ) {
memcpy (str, sum, len);
for ( int j = 1; j <= i - 1; ++j ) {
index = len - 1;
int carry = 0;
do {
int digit = (sum[index] - '0') + (str[index] - '0') + carry;
carry = 0;
if ( digit > 9 ) {
carry = 1;
digit %= 10;
}
sum[index] = digit + '0';
--index;
}
while ( index >= 0 );
}
printf ("%2i! = ", i);
for ( index = 0; sum[index] == '0'; ++index )
printf ("%c", '.');
for ( ; index < len; ++index )
printf ("%c", sum[index]);
printf ("\n");
}
return 0;
}

Why Is This Factorial Algorithm Not Accurate
There's nothing wrong in your algorithm as such. It is just that the data types you use have a limit for the highest number they can store. This will be a problem no matter which algorithm you choose. You can change the data types from float to something like long double to hold something bigger. But eventually it will still start failing once the factorial value exceeds the capacity of that data type. In my opinion, you should put an a condition in your factorial function to return without calculating anything if the passed in argument is greater than a value that your chosen datatype can support.

float can represent a wider range of numbers than int, but it cannot represent all the values within that range - as you approach the edge of the range (i.e., as the magnitudes of the values increase), the gap between representable values gets wider.
For example, if you cannot represent values between 0.123 and 0.124, then you also cannot represent values between 123.0 and 124.0, or 1230.0 and 1240.0, or 12300.0 and 12400.0, etc. (of course, IEEE-754 single-precision float gives you a bit more precision than that).
Having said that, float should be able to represent all integer values up to 224 exactly, so I'm going to bet the issue is in the printf call - float parameters are "promoted" to double, so there's a representation change involved, and that may account for the lost precision.
Try changing the return type of factorial to double and see if that doesn't help.
<gratuitous rant>
Every time I see a recursive factorial function I want to scream. Recursion in this particular case offers no improvement in either code clarity or performance over an iterative solution:
double fac( int x )
{
double result = 1.0;
while ( x )
{
result *= x--;
}
return result;
}
and can in fact result in worse performance due to the overhead of so many function calls.
Yes, the definition of a factorial is recursive, but the implementation of a factorial function doesn't have to be. Same for Fibonacci sequences. There's even a closed form solution for Fibonacci numbers
Fn = ((1 + √5)n - (1 - √5)n) / (2n * √5)
that doesn't require any looping in the first place.
Recursion's great for algorithms that partition their data into relatively few, equal-sized subsets (Quicksort, tree traversals, etc.). For something like this, where the partitioning is N-1 subsets of 1 element? Not so much.
</gratuitous rant>

Related

Logarithm calculator

I'm trying to make a logarithm calculator and got stuck—it doesn't print out a value. The problem may be at lines 15 or 24 or both. How can I make it print the value (all written in C).
Here's the full code:
#include <stdio.h>
#include <stdlib.h>
// Finds base 10 logarithms
int main()
{
float result;
float base = 10.0;
float multiplier = 1.0;
// float counter1 = 0.0;
// float counter2 = 0;
printf("Input result: ");
scanf("%l", result);
// Solves for all results above the base
if(result > base) {
while(result > multiplier) {
multiplier = multiplier * multiplier; // the multiplier has to check non-whole numbers
multiplier += 0.001;
} // division
}
printf("Your exponent is: %l \n", &multiplier);
printf("Hello mathematics!");
return 0;
}
All help appreciated,
Xebiq
you should delete & in printf,and add & in scanf.
printf("Your exponent is: %f \n", multiplier);
scanf("%f", &result);
and use %f in them.
and with base 10 I suggest this function to calculate log:
unsigned int Log2n(unsigned int n)
{
return (n > 1) ? 1 + Log2n(n / 10) : 0;
}
also you should know about Floating-point numbers here:
multiplier += 0.001;
probably exactly 0.001 won't be added to multiplier when I debugged this 0.00100005 was being add to multiplier in my compiler.(which will affect multiplying)
In printf remove '&' and in scanf add '&' before variable.

I wrote a program to print all primes number up-to a given a number

#include<stdio.h>
float abso(float a)
{
if(a<0.0)
return(-1*a);
else
return a;
}
int sqert(int x)
{
float x1 = (float)x;
float g1, g2;
g1 = x1/2.0;
g2 = x1/g1;
double e=0.000000001;
int sr;
while(abso(g1-g2)>=e)
{
g2 = (g1+x1/g1)/2.0;
g1 = x1/g2;
}
sr = (int)g1;
return(sr);
}
int main()
{
int num;
//num = 0;
printf("Enter a num between 1 and 1000 ");
scanf("%d",&num);
//printf("hello");
int flag;
flag = 0;
int i;
i = 2;
int m, j;
m = j = 0;
while(i<=num)
{
flag = 1;
if(i==2)
{
printf("%d ",i);
i++;
}
else if(i==3)
{
printf("%d ",i);
i= i+2;
}
else if(i>3)
{
m = sqert(i);
for(j=2;j<=m;j++)
{
if((i%j) == 0)
{
flag = 0;
break;
}
}
if(flag == 0)
{
i = i + 2;
continue;
}
if(j==m+1)
printf("%d ",i);
i = i + 2;
}
}
printf("\n");
return(0);
}
Here sqert function is taking square root of the input value and abso function is taking the absoulte value of given value.
The logic used is simple we are iterating to the square root of that number and then check for every number if it is divisible by any other number than itself then it is not a prime number else it is a prime number.
But this program is working only for value upto 5. After that it is not printing anything. It is not printing the entered number also.
Any help would be appreciated.
In your code, you are trying to compare float with double.
while(abso(g1-g2)>=e)
This is not correct because of the difference in precision between float and double.
double has 2 times more precision than float.
float is a 32 bit IEEE 754 single precision floating point number
(1 bit for the sign, 8 bits for the exponent, and 23* for the value),
i.e. float has 7 decimal digits of precision.
double is a 64 bit IEEE 754 double precision floating point number
(1 bit for the sign, 11 bits for the exponent, and 52* bits for the value),
i.e. double has 15 decimal digits of precision.
Declare e as float and make sure it is assigned a value that fits with the precision of float.
Something like:
float e = 0.00001;
Then your code will work as intended.
#EricPostpischil in the comments said that the sqert function may not always return the correct approximation. This is correct.
So it is better to use sqrt from math.h which works perfectly instead of sqert.

How do I multiply a long integer with different numbers in C program?

I am very new to C programming and I am writing a program which takes a number which is suppose to be 9 digits long. After this I multiply each digit with either 1 or 2. I am using arrays to ask user to enter their numbers. I would like to know if there is a way to multiply those 9 numbers with different numbers as one integer instead of using arrays? Here is my code with arrays:
#include <stdio.h>
int main(void) {
int sin_num[9];
int num1;
int num2, num11, num12;
int num3, num4, num5, num6, num7, num8, num9, num10;
for(num1=0; num1<9; num1++) {
printf("Enter your SIN number one by one:");
scanf("%d", &sin_num[num1]);
}
num2 = sin_num[0] * 1;
num3 = sin_num[1] * 2;
num4 = sin_num[2] * 1;
num5 = sin_num[3] * 2;
num6 = sin_num[4] * 1;
num7 = sin_num[5] * 2;
num8 = sin_num[6] * 1;
num9 = sin_num[7] * 2;
num10 = sin_num[8] * 1;
Right now I am doing this:
element 1 * 1
element 2 * 2
element 3 * 1
But how can I do, lets say if I enter 123456789 multiply with different numbers:
123456789
121212121
Well I couldn't much understand what you were asking. Anyways hope this is what you are looking for.....
#include<stdio.h>
int main()
{
long int nine_digit_num;
int step=100000000;
int digit,input_num,i;
printf("Enter 9 digit number:\n");
scanf("%ld",&nine_digit_num);
for(i=1;i<=9;i++)
{
printf("Enter a number to multiply with the %d digit:\n",i);
scanf("%d",&input_num);
digit=nine_digit_num/step; // this and the next step are used to
digit=digit%10; // obtain the individual digits.
printf("%d*%d=%d\n",digit,input_num,digit*input_num);
step=step/10;
}
return 0;
}
I'm sure there are Luhn algorithm solutions already written that you could reference, but I'm going to invent my own right now just to have a walkthrough.
Since your input is only 9 digits, it will fit in a plain 32 bit variable. I'll use unsigned on the assumption it's 32 bits or bigger, but for production code, you'd likely want to use inttypes.h uint32_t and associated scanf macros.
#include <stdio.h>
int main(void) {
unsigned sin_num, checksum, digit;
int i;
printf("Enter your SIN as a 9 digit number using only digits:\n");
if (scanf(" %9u", &sin_num) < 1) ... do error handling or just exit ...
for (i = 0; sin_num; ++i) {
digit = sin_num % 10;
sin_num /= 10;
if (i & 1) { // Double odd digits (might have this backwards; check me for your case
digit *= 2;
if (digit >= 10) digit = digit % 10 + digit / 10; // Luhn carry is strange
}
checksum += digit;
}
... do whatever else you need to do ...
It's not a single mathematical operation because Luhn's carry is too weird for magic number tricks, but it's still much more straightforward than a bunch of single digit scanf calls and array storage.

Any decent way of printing out floats and doubles with commas?

I'm working on a program that regards with currency. Ive been finding a solution to display money values decently like this:
9,999.99 USD
Remember when assigning a certain variable with a value (money), you musn't insert commas.
I.e.:
double money=9999.99;
And when accessing it;
printf("%.2l USD",money);
Which will output:
9999.99 USD
This is not what I want, especially on bigger amounts exceeding the hundredth, thousandth, millionth, or even billionth place value.
Now I can't find any solution than printing out the desired output directly on the printf.
printf("9,999.99");
Which is undesirable with many variables.
Can anyone help me out?
Please take a look and printf manual page taking note of the following bit:
*"For some numeric conversions a radix character ("decimal point") or thousands' grouping character is used. The actual character used depends on the LC_NUMERIC part of the locale. The POSIX locale uses '.' as radix character, and does not have a grouping character. Thus,
printf("%'.2f", 1234567.89);
results in "1234567.89" in the POSIX locale, in "1234567,89" in the nl_NL locale, and in "1.234.567,89" in the da_DK locale."*
This can be changed by the function setlocale
There is a function, strfmon which might be able to help you
First, don't use floating-point types to represent money because normally floating-point types are binary and as such cannot represent all decimal fractions (cents) exactly, further these types are prone to rounding errors. Use integers instead and count cents instead of dollars.
#include <stdio.h>
#include <limits.h>
unsigned long long ConstructMoney(unsigned long long dollars, unsigned cents)
{
return dollars * 100 + cents;
}
void PrintWithCommas(unsigned long long n)
{
char s[sizeof n * CHAR_BIT + 1];
char *p = s + sizeof s;
unsigned count = 0;
*--p = '\0';
do
{
*--p = '0' + n % 10;
n /= 10;
if (++count == 3 && n)
{
*--p = ',';
count = 0;
}
} while (n);
printf("%s", p);
}
void PrintMoney(unsigned long long n)
{
PrintWithCommas(n / 100);
putchar('.');
n %= 100;
putchar('0' + n / 10);
putchar('0' + n % 10);
}
int main(void)
{
PrintMoney(ConstructMoney(0, 0)); puts("");
PrintMoney(ConstructMoney(0, 1)); puts("");
PrintMoney(ConstructMoney(1, 0)); puts("");
PrintMoney(ConstructMoney(1, 23)); puts("");
PrintMoney(ConstructMoney(12, 34)); puts("");
PrintMoney(ConstructMoney(123, 45)); puts("");
PrintMoney(ConstructMoney(1234, 56)); puts("");
PrintMoney(ConstructMoney(12345, 67)); puts("");
PrintMoney(ConstructMoney(123456, 78)); puts("");
PrintMoney(ConstructMoney(1234567, 89)); puts("");
return 0;
}
Output (ideone):
0.00
0.01
1.00
1.23
12.34
123.45
1,234.56
12,345.67
123,456.78
1,234,567.89
If you're using the standard library, there's no way to do this -- you have to write some code that does it by hand.
I would recommend multiplying the value by 100, casting to integer, and printing the digits with separators as needed -- it's much easier to handle individual digits on an integer.
The following code, for instance, will fill a char * buffer with the string representation of the value you have:
void formatString (double number, char * buffer) {
if (number < 0) {
*buffer = '-';
formatString(number, buffer + 1);
return;
}
unsigned long long num = (unsigned long long) (number * 100);
unsigned long long x; // temporary storage for counting the digits
unsigned char digits;
for (x = num / 1000, digits = 1; x; digits ++, x /= 10);
// counts the digits, also ensures that there's at least one digit
unsigned char pos; // digit position
for (pos = 1, x = 100; pos < digits; pos ++, x *= 10);
// reuses x as a value for extracting the digit in the needed position;
char * current = buffer;
for (pos = digits; pos; pos --) {
*(current ++) = 48 + (num / x);
// remember 48 + digit gives the ASCII for the digit
if (((pos % 3) == 1) && (pos > 1)) *(current ++) = ',';
num %= x;
x /= 10;
}
*(current ++) = '.';
*(current ++) = 48 + num / 10;
*(current ++) = 48 + num % 10;
*current = 0;
}

How can I convert a float/double to ASCII without using sprintf or ftoa in C?

How can I convert a float/double to ASCII without using sprintf or ftoa in C?
I am using an embedded system.
The approach you take will depend on the possible range of values. You certainly have some internal knowledge of the possible range, and you may only be interested in conversions within a more narrow range.
So, suppose you are only interested in the integer value. In this case, I would just assign the number to an int or long, at which point the problem becomes fairly obvious.
Or, suppose the range won't include any large exponents but you are interested in several digits of fraction. To get three digits of fraction, I might say int x = f * 1000;, convert x, and then insert the decimal point as a string operation.
Failing all of the above, a float or double has a sign bit, a fraction, and an exponent. There is a hidden 1 in the fraction. (The numbers are normalized until they have no leading zeroes, at which point they do one more shift to gain an extra bit of precision.) The number is then equal to the fraction (plus a leading '1') * 2 ** exponent. With essentially all systems using the IEEE 754 representation you can just use this Wikipedia IEEE 754 page to understand the format. It's not that different from just converting an integer.
For single precision, once you get the exponent and fraction, the valueNote 1 of the number is then (frac / 223 + 1) * 2exp, or frac * 2exp - 23 + 2exp.
Here is an example that should get you started on a useful conversion:
$ cat t.c
#include <stdio.h>
void xconvert(unsigned frac)
{
if (frac) {
xconvert(frac / 10);
printf("%c", frac % 10 | '0');
}
}
void convert(unsigned i)
{
unsigned sign, exp, frac;
sign = i >> 31;
exp = (i >> (31 - 8)) - 127;
frac = i & 0x007fffff;
if (sign)
printf("-");
xconvert(frac);
printf(" * 2 ** %d + 2 ** %d\n", exp - 23, exp);
printf("\n");
}
int main(void)
{
union {
float f;
unsigned i;
} u;
u.f = 1.234e9;
convert(u.i);
return 0;
}
$ ./a.out
1252017 * 2 ** 7 + 2 ** 30
Note 1. In this case the fraction is being converted as if the binary point was on the right instead of the left, with compensating adjustments then made to the exponent and hidden bit.
#include<stdio.h>
void flot(char* p, float x)
{
int n,i=0,k=0;
n=(int)x;
while(n>0)
{
x/=10;
n=(int)x;
i++;
}
*(p+i) = '.';
x *= 10;
n = (int)x;
x = x-n;
while((n>0)||(i>k))
{
if(k == i)
k++;
*(p+k)='0'+n;
x *= 10;
n = (int)x;
x = x-n;
k++;
}
/* Null-terminated string */
*(p+k) = '\0';
}
int main()
{
float x;
char a[20]={};
char* p=&a;
printf("Enter the float value.");
scanf("%f",&x);
flot(p,x);
printf("The value=%s",p);
getchar();
return 0;
}
Even in an embedded system, you'd be hard pressed to beat the performance of ftoa. Why reinvent the wheel?

Resources