Division issues in C - c

I don't really know how to explain this (that's why the title was to vague) but I need a way to make C divide in a certain way, I need to make c divide without any decimals in the answer (besides the remainder) for example;
Instead of 5.21 / .25 = 20.84
I need this 5.21 / .25 = *20* Remainder = *.21*
I found out how to find the remainder with Fmod() but how do I find the 20?
Thanks ~

how about using implicit casts?
float k = 5.21 / .25;
int n = k;
k -= n;
results in
k = .84
n = 20
using only ints will also do the job if you don't need the remainder
int k = 5.21 / .25
will automatically truncate k and get k = 20

Use double modf(double value, double *iptr) to extract the integer portion of a FP number.
The modf functions break the argument value into integral and fractional parts, each of which has the same type and sign as the argument. C11 ยง7.12.6.12 2
#include <math.h>
#include <stdio.h>
int main() {
double a = 5.21;
double b = 0.25;
double q = a / b;
double r = fmod(a, b);
printf("quotient: %f\n", q);
printf("remander: %f\n", r);
double ipart;
double fpart = modf(q, &ipart);
printf("quotient i part: %f\n", ipart);
printf("quotient f part: %f\n", fpart);
return 0;
}
Output
quotient: 20.840000
remander: 0.210000
quotient i part: 20.000000
quotient f part: 0.840000
Using int is problematic due to a limited range, precision and sign issues.

Related

How to round DOWN to 2 decimal in C

So I am trying to round DOWN to 2 decimal places in C - EDIT: I actually need to change the value, not just display it to 2 decimals.
For example:
double x = 0.1234;
x = 0.12;
double y = 3.14159;
y = 3.14;
Is the an integrated function in <math.h> similar to floor(), or is there another way to do this?
Well I need to value to change so I used x = (double)((int)(x*100))/100;
This works, but you are limited to a relatively low range, i.e: 123456789 * 100 overflows.
Check if modf helps:
#include <stdio.h>
#include <math.h>
double dec2(double number)
{
double fractpart, intpart;
fractpart = modf(number, &intpart);
return intpart + round(fractpart * 100) * 0.01;
}
int main(void)
{
printf("%f\n", dec2(0.1234));
printf("%f\n", dec2(3.14159));
return 0;
}
Output:
0.120000
3.140000
If you want to display a float or double with 2 decimal places, specify a precision of 2 when using the %f format specifier.
printf("x=%.2f", x);

Is it possible to replace a double number and write the program using only integers in C, with the same output?

Is it possible to write a program like this, using only the integer type and the standard library <stdio.h> in C? The output of the remainder must be displayed as a decimal number with two numbers behind the comma.
#include <stdio.h>
int num1 = 0;
int num2 = 1;
int num3 = 6;
int num4 = 3;
int num5 = 7;
int num6 = 3;
int num7 = 9;
int num8 = 8;
int sum, product, Result;
double division;
int main()
{
sum = num1 + num2 + num3 + num4;
product = num5 * num6 * num7;
Result = ((++product) - (sum++)) * sum;
int Integer_division = Result / (num8+ 1);
int Remainder = Result % (num8+ 1);
double division = Result / (num8+ 1);
printf("Result = %d\n", Result);
printf("Integer division = %d\n", Integer_division);
printf("Remainder = %d\n", Remainder);
printf("Division = %.02f\n", division);
return 0;
}
I was thinking about splitting it into two halves and printing it with a comma in between(%d.%d)
but that sounds like my last resort...
Thanks in advance.
To print floating-point like text from integers requires the sign, while-number part and the fraction part
char *sign = Result<0 ? "-":"";
int whole = abs(Integer_division);
char decimal_point = ','; // behind the comma.
int hundredths = abs(Remainder *100/(num8+ 1)); // Convert fraction to
1/100ths
// now print it
printf("%s%d%c%02d", sign, whole, decimal_point, hundredths);
Yet this displays only a truncated result. To round is work.
The usual way to mimic floating point output using integers it to consider the value as a fraction of 2 integer parts: numerator, denominator that needs scaling (e.g. x100 for .00 display) . For simplicity, assume denominator > 0.
First step is rounding due to finite display precision. Since the next step will involve an integer divide "truncate toward zero" and floating-point like display is usually "round to nearest", code needs to add a signed, unscaled 0.5 or one-half the denominator.
For simplicity, assume denominator > 0 and is odd so we can avoid half-way cases (even more work). Also assume no int overflow to avoid more work.
int numerator = Result;
int denominator = num8+ 1;
int scale = 100; // to print to 0.xx
int scaled_numerator = numerator * scale;
int scaled_half = denominator / 2;
if (scaled_numerator < 0) scaled_half = -scaled_half;
int rounded_scaled_numerator = scaled_numerator + scaled_half;
Now divide
int scaled_value = rounded_scaled_numerator/denominator;
char *sign = scaled_value<0 ? "-":"";
scaled_value = abs(scaled_value);
int whole = scaled_value / scale;
char decimal_point = ',';
int hundredths = scaled_value % scale;
printf("%s%d%c%02d", sign, whole, decimal_point, hundredths);

Calculating Maxwell-Boltzmann Distribution

I am trying to calculate Maxwell-Boltzmann Distribution but this code gives 0.00000, what is the problem?
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
float e=2.718228183, pi=3.14159265, m=2.66*pow(10,-23), t, k=1.38*pow(10,-23), v, result;
scanf("%f %f", &t, &v);
result = sqrt(pow( m / (2*pi*k*t), 3)) * 4 * pi * pow(v,2) * pow(e, -(m * pow(v,2)) / (2*k*t));
printf("%f", result);
}
As described in the comments, the use of float together with the reduced precision of the constants give a result that is not representable anymore as a float. Changing the data type to double alone gives two decimal digits of accuracy. If we use exp, more digits for pi and do a bit of recombination of the computations we get 12 digits of accuracy. E.g.:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
double pi = 3.1415926535897932384626433832795028842, m = 2.66e-23, k =
1.38e-23;
double t, v, v2, dkt, result;
// check omitted
scanf("%lf %lf", &t, &v);
v2 = v * v;
dkt = 2 * k * t;
result = pow(m / (pi * dkt), 3 / 2.0) * 4 * pi * v2 * exp(-(m * v2) / (dkt));
printf("%.20g\n", result);
return 0;
}
The result from Pari/GP is 8.1246636077915008261803395870165527173e-9 and the result we get with the code above is 8.1246636077914841125e-09. Without the intermediate results v2, dkt and the replacement of sqrt we got 8.1246636077914824582e-09, not much of a difference, especially with accuracy where it gained nothing.
If you want the full 16 decimal digits of accuracy you need to take the whole thing apart and take a different approach.
replace
double pi=acos(-1.);
instead of
double pi=3.1415926535897932384626433832795028842;

10k by 10k matrix malloc curiousity in c [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to sum a large number of float number?
I have a matrix 'x' that is 10,000 elements by 10,000 elements.
In the first case I declare the matrix like:
int n = 10000;
unsigned int size_M = n*n;
unsigned int mem_size_M = sizeof(int)*size_M;
int* x = (int*)malloc(mem_size_M);
Step (1) The matrix is initialized:
for(i=0;i<n;i++)
for(j=0;j<n;j++)
x[i*n+j] = 1;
Step (2) Sum the elements of the matrix and print the total:
for(i=0i<n;i++)
for(j=0j<n;j++)
sum +=x[i*n+j];
printf("sum: %d \n", sum);
As I would expect the above code prints 'sum: 100000000 '.
However if I declare the matrix like:
int n = 10000;
float size_M = n * n;
float mem_size_M = sizeof(float) * size_M;
float* x = (float*)malloc(mem_size_M);
And again perform the steps 1 and 2 the correct answer is not printed out, but '16777216' instead. Why is this?
ANSWER: To get the appropriate answer do a type conversion...
sum +=(int)x[i*n+j];
This happens because of the precision limitations of the float type. You can't just add 1.0 to float with value > 16777216 (2^24), but you can add 2.0, or 0.1:
#include <stdio.h>
int main(void)
{
float f = 16777220;
printf("f = %f\n", f + 1);
printf("f = %f\n", f + 2);
printf("f = %f\n", f + 0.1);
return 0;
}
The IEEE-754 standard floating-point numbers have have 4 bytes, consisting of a sign bit, an 8-bit excess-127 binary exponent, and a 23-bit mantissa. It's a bit complicated to explain precisely why it happens, but I can say that this is a extreme case when operation error reaches its maximum.

Manually implementing a rounding function in C

I have written a C program (which is part of my project) to round off a float value to the given precision specified by the user. The function is something like this
float round_offf (float num, int precision)
What I have done in this program is convert the float number into a string and then processed it.
But is there a way to keep the number as float itself and implement the same.
Eg. num = 4.445 prec = 1 result = 4.4
Of course there is. Very simple:
#include <math.h>
float custom_round(float num, int prec)
{
int trunc = round(num * pow(10, prec));
return (float)trunc / pow(10, prec);
}
Edit: it seems to me that you want this because you think you can't have dynamic precision in a format string. Apparently, you can:
int precision = 3;
double pie = 3.14159265358979323648; // I'm hungry, I need a double pie
printf("Pi equals %.*lf\n", precision, pie);
This prints 3.142.
Yes:
float round_offf(float num, int precision)
{
int result;
int power;
power = pow(10, precision + 1);
result = num * power;
if ((result % 10) > 5)
result += 10;
result /= 10;
return ((float)result / (float)power);
}

Resources