My C++ code not showing floating point value [duplicate] - c++

This question already has answers here:
Why does this division result in zero?
(6 answers)
Why do my division results appear to be off?
(2 answers)
Closed 9 years ago.
My code is not showing exact float value means number after point is not displayed by the code
I am using Turbo C for sum up the series 1 + 1/3 + 1/5 + 1/7 + 1/9+….. Up to N terms
#include<iostream.h>
#include<conio.h>
void main()
{
int k=0;
int m=0;
int s=1;
clrscr();
cout<<"Enter the limit of the series: ";
cin>>m;
for(int j=1;j<=m;j=j+2)
{
m=1/j;
s+=m;
}
cout<<"Sum of the given series is: "<<s;
getch();
}

You're using int which only displays Integer (ie whole number) values. It truncates any decimal places because it assumes you don't want them. Try using float or double instead.

Integer division will not give you anything other than integer results.
You need to:
Change s to a float or double.
change m to a float or double.
Change 1 in 1/j to 1.0f or 1.0 (for float and double respectively).
Now, you probably also want to use a different variable than m for your input and for-loop limit variable, so that you don't stop too quickly once the calculation starts.

Use the type double for variables m and s.

Here are the variables you declared in your code.
int k=0;
int m=0;
int s=1;
Where exactly do you think you have a floating point number?
(which would have to be of type float or double)
You do know that int means integer, right?
(eg. Not a floating point number)

Related

Why isn't this C funtion calculating sqrt working for decimals? [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 1 year ago.
#include <iostream>
float calculating_root(float N, float root_N, float increment)
{
int safety=1;
while(safety==1)
{
if (N == (root_N*root_N))
{
safety=0;
return root_N;
}
else if(N<((root_N+increment)*(root_N+increment)))
{
safety=0;
return calculating_root(N,root_N, increment*0.1);
}
root_N=root_N+increment;
}
}
int main()
{
float N, root_N=0.0, increment=1000.0;
scanf("%f",&N);
float x = calculating_root(N, root_N, increment);
printf("\n%g\n",x);
return 0;
}
I've been thinking about it for such a long time. I guess I don't have other ideas, everything seems perfect? Does anyone sees a mistake?
Using == for comparing floating point numbers that you calculated is not advised. Especially in this case N might actually be a number that is not representable by any float a such that a*a == N.
so instead of
N == (root_N*root_N)
try to use something like
fabs(N-(root_N*root_N)) < epsilon
Where epsilon is your acceptable rounding error. You could choose something like const float epsilon = 0.000001f. I think in this case you might need something above the machine epsilon, because you're potentially accumulating the error.
You could also improve precision somewhat by using double instead of float. That will however not replace the need for the epsilon, only allow you to choose a lower epsilon.

Why can't we compare a float value with some numerical value [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 2 years ago.
I tried the below code i assigned a float value to variable and i compared it with a floating point value but it did not gave the desired output.
Here as a==13.30 is true i thought it will print "a" instead it prints "5"
#include<iostream>
using namespace std;
int main()
{
float a=13.30;
if(a==13.30)
cout<<a;
else
cout<<"5";
}
output is "5" not "a"
13.30 is a double. Try comparing against 13.30f.
0.30 cannot be represented exactly and since double has a higher precision, it is not an exact match.
Ofcourse you can simply compare float value with some numerical value , but just because you can , it doesn't mean you should. It's classical example of that .
There are many problems regarding storing exact floating point value in memory , due to hardware restrictions , this issue regarding storing exact floating point value in memory exist in virtually all the programming languages and platform . A better way to equating floating point values is checking if the difference of two values that you need to compare is less than some other very small number . In your code , you can implement that as ,
#include <iostream>
using namespace std;
const double EPSILON = 1e-5;
int main()
{
float a = 13.30;
if (abs(a - 13.30) < EPSILON)
cout << a;
else
cout << "5";
}
Now , this code will output 13.30 , here EPSILON is used as a very small double value to compare with the difference .
To know more about why this issue is prevalent read , Is-floating-point-math-broken and Why are floating point numbers inaccurate

Print 2 decimals from float value [duplicate]

This question already has answers here:
C++ program converts fahrenheit to celsius
(8 answers)
Closed 7 years ago.
First of all, I want to say sorry because I think the doubt is so trivial... but I'm new programming in C++.
I have the following code:
int a = 234;
int b = 16;
float c = b/a;
I want to print the result from float c with 2 decimals (the result should be 0.06) but I don't get the expected result.
Can anyone can help me? I tried using CvRound() and setPrecision() but nothing works like I expect or, in my case, I don't know how to do them working.
The problem is actually blindingly simple. And has NOTHING whatsoever do do with settings such as precision.
a and b are of type int, so b/a is also computed to be of type int. Which involves rounding toward zero. For your values, the result will be zero. That value is then converted to be float. An int with value zero, when converted to float, gives a result of 0.0. No matter what precision you use to output that, it will still output a zero value.
To change that behaviour convert one of the values to float BEFORE doing the division.
float c = b/(float)a;
or
float c = (float)b/a;
The compiler, when it sees a float and and an int both participating in a division, converts the int to float first, then does a division of floats.
int a = 234;
int b = 16;
float c = b/(float)a;
float rounded_down = floorf(c * 100) / 100; /* floor value upto two decimal places */
float nearest = roundf(c * 100) / 100; /* round value upto two decimal places */
float rounded_up = ceilf(c * 100) / 100; /* ceiling value upto two decimal places */
If you just want to print the result, you can use a printf() formatting string to round:
printf("c = %.2f\n", number, pointer);
Otherwise, if you need c to calculate another value, you shouldn't round the original value, only the one to print.
try this:
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int a = 234;
int b = 16;
float c = float(b)/a;
cout<<fixed<<setprecision(2)<<c;
return 0;
}
Previously when c = b/a since a and b are integers so by integer division we were getting answer as 0 as per your program.
But if we typecast one of the variable(a or b) to float we will obtain decimal answer.
Number of digits after decimal may or may not be 2. To ensure this we can use fixed and setprecision. fixed will ensure that number of digits after decimal will be fixed. setprecision will set how many digits to be there after decimal.

Discrepancy in the value stored in two variables having the same integral part [duplicate]

This question already has answers here:
Wrong answer while calculating the nth root of number in cpp
(3 answers)
Closed 8 years ago.
I was trying to find the cube root of 10^12 and used the following code in c++. To my surprise, the value returned was different . Can anyone help me with this problem.
Output: 10000 9999
int y;
double x=pow(1000000000000, 1./3);
double r=floor(x);
y=(int)r;
cout<<x<<" ";
cout<<y;
Your floor operation is the issue here. What if the returned value is actually (due to precision errors) x = 9999.999? floor(x) would return 9999 while cout << x directly prints the floating point number based on it's internal precision setting, so cout << x does implicit rounding which is why 10000 is displayed there.
Try rounding x properly to an int by doing this:
int y;
double x=pow(1000000000000, 1./3);
y=(int)(x+0.5); //Proper rounding
cout<<x<<" ";
cout<<y;
return 0;
double x=pow(1000000000000, 1./3);
is just bad 1/3 can not be displayed with double.
when working with double result are always interesting to say the least. 0.001 + 0.001 may just be 0.0

Losing Double Precision when multiplying by multiple of 10 [duplicate]

This question already has answers here:
Precision loss with double C++
(4 answers)
Closed 9 years ago.
So I have the following code
int main(){
double d;
cin>>d;
while(d!=0.00)
{
cout<<d<<endl;
double m = 100*d;
int n = m;
cout<<n<<endl;
cin>>d;
}
return 0;}
When I enter the input 20.40 for d the value of n comes out to be 2039 instead of 2040.
I tried replacing int n = m with int n = (int) m but the result was the same.
Is there any way to fix this. Thanks in advance.
Your code truncates m but you need rounding. Include cmath and use int n = round(m).
Decimal values can, in general, not be represented exactly using binary floating points like double. Thus, the value 20.40 is represented as an approximation which can be used to restore the original value (20.4; the precision cannot be retained), e.g., when formatting the value. Doing computations with these approximated values will typically amplify the error.
As already mentioned in one of the comments, the relevant reference is the paper "What Every Computer Scientist Should Know About Floating-Point Arithmetic". One potential way out of your trouble is to use decimal floating points which are, however, not yet part of the C++ standard.
Single and double presicion floating point numbers are not stored the same way as integers, so whole numbers (e.g. 5, 10) may actually look like long decimals (e.g. 4.9999001, 10.000000001). When you cast to an int, all it does is truncate the whole number. So, if the number is currently represented as 4.999999999, casting it to an int will give you 4. std::round will provide you with a better result most of the time (if the number is 4.6 and you just want the whole number portion, round will not work well). The bigger question is then: what are you hoping to accomplish by casting a double to an int?
In general, when dealing with floating point numbers, you will want to use some epsilon value that is your minimum significant digits. So if you wanted to compare 4.9999999 to 5, you would do (pseudo-code): if abs(5 - 4.9999999) < epsilon, return 5.
Example
int main()
{
double d;
std::cin >> d;
while (std::fabs(d - 0.0) > DBL_EPSILON)
{
std::cout << d << std::endl;
double m = 100 * d;
int n = static_cast<int>(m);
if (std::fabs(static_cast<double>(n) - m) > DBL_EPSILON)
{
n++;
}
std::cout << n << std::endl;
std::cin >> d;
}
return 0;
}
Casting double to int truncates value so 20.40 is probably 20.399999 * 100 is 2039.99 because double is not base 10. You can use round() function that will not truncate but will get you nearest int.
int n = round(m);
Floating point numbers can't exactly represent all decimal numbers, sometimes an approximation is used. In your example the closest possible exact number is 20.39999999999999857891452847979962825775146484375. See IEEE-754 Analysis for a quick way to see exact values.
You can use rounding, but presumably you're really looking for the first two digits truncated. Just add a really small value, e.g. 0.0000000001 before or after you multiply.