C++ doesn't show numbers with big decimals - c++

I wrote a program of which the result made me wonder.
I have a double number with 3 decimals, but I need to change it to 2 decimals.
First I multiplied it with 100, then I changed it to an int, then I divided it by 100, but I don't know why
the result is wrong
input: 9.857
output is: 9.8499999999999996
Here is my code:
#include <iostream>
#include <cstdio>
using namespace std;
int main(){
double sum = 9.857, temp = 0;
temp = int(sum * 100);
temp = int(temp);
sum = temp / 100;
printf("%.16f\n", sum);
}
input: 9.857
output is: 9.850000000000000
Second code:
#include <iostream>
#include <cstdio>
using namespace std;
int main(){
double sum = 9.857, temp = 0;
temp = int(sum * 100);
temp = int(temp);
sum = temp / 100;
printf("%.15f\n", sum);
}
Why are the answers of these two code snippets different?

In addition to floating point arithmetic, you are also using the unsafe printf-family of functions despite including <iostream>. The proper way to limit the precision of your output value in C++ is to set the ostream's precision value:
Example
#include <iostream>
int main()
{
double sum = 9.857, temp = 0;
std::cout.precision(4);
std::cout << "Value = " << sum << std::endl;
std::cout.precision(3);
std::cout << "Value = " << sum << std::endl;
std::cout.precision(2);
std::cout << "Value = " << sum << std::endl;
return 0;
}
If you wanted to do it in C, it would look like this:
Example
#include <stdio.h>
int main()
{
double sum = 9.857, temp = 0;
printf("Value = %.3f\n", sum);
printf("Value = %.2f\n", sum);
return 0;
}
If you are looking for exact values, floating point types are not the right type to use due to how they are stored (they will not be exact). This means that attempting to show 15-digits beyond the decimal is not likely to give you the same result as your input for many cases.

Related

sum of Maclaurin series c++

I am struggling to make this equation equals to each other because of a bad understanding of mathematics.
The problem is that the equation does not equal to each other
here is my code for better understand
#include <iostream>
#include <ccomplex>
using std::cout;
int main() {
int n = 8;
double sum = 0.0;
unsigned long long fact =1;
for (int i = 1; i <= n; i++)
{
fact *= 2*i*(2*i-1);
sum += 1.0 / fact;
}
std::cout << "first equation " << sum << std::endl;
double e = M_E;
double st = 1.0/2.0*(e + (1.0/e));
std::cout <<"second equation " << st << std::endl;
return 0;
}
the output
first equation 0.543081
second equation 1.54308
The result it nearly It must be at least equal before the comma,
You don't account for n = 0, which yields 0! and thus 1. Therefore, you need to add 1 to sum.

Translation from binary into decimal numbers in C++

I tried to build a function that calculates a binary number stored in a string into a decimal number stored in a long long. I'm thinking that my code should work but it doesn't.
In this example for the binary number 101110111 the decimal number is 375. But my output is completely confusing.
Here is my code:
#include <string>
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <string.h>
int main() {
std::string stringNumber = "101110111";
const char *array = stringNumber.c_str();
int subtrahend = 1;
int potency = 0;
long long result = 0;
for(int i = 0; i < strlen(array); i++) {
result += pow(array[strlen(array) - subtrahend] * 2, potency);
subtrahend++;
potency++;
std::cout << result << std::endl;
}
}
Here is the output:
1
99
9703
894439
93131255
9132339223
894974720087
76039722530902
8583669948348758
What I'm doing wrong here?
'1' != 1 as mentioned in the comments by #churill. '1' == 49. If you are on linux type man ascii in terminal to get the ascii table.
Try this, it is the same code. I just used the stringNumber directly instead of using const char* to it. And I subtracted '0' from the current index. '0' == 48, so if you subtract it, you get the actual 1 or 0 integer value:
auto sz = stringNumber.size();
for(int i = 0; i < sz; i++) {
result += pow((stringNumber[sz - subtrahend] - '0') * 2, potency);
subtrahend++;
potency++;
std::cout << result << std::endl;
}
Moreover, use the methods provided by std::string like .size() instead of doing strlen() on every iteration. Much faster.
In a production environment, I would highly recommend using std::bitset instead of rolling your own solution:
std::string stringNumber = "1111";
std::bitset<64> bits(stringNumber);
bits.to_ulong();
You're forgetting to convert your digits into integers. Plus you really don't need to use C strings.
Here's a better version of the code
int main() {
std::string stringNumber = "101110111";
int subtrahend = 1;
int potency = 0;
long long result = 0;
for(int i = 0; i < stringNumber.size(); i++) {
result += pow(2*(stringNumber[stringNumber.size() - subtrahend] - '0'), potency);
subtrahend++;
potency++;
std::cout << result << std::endl;
}
}
Subtracting '0' from the string digits converts the digit into an integer.
Now for extra credit write a version that doesn't use pow (hint: potency *= 2; instead of potency++;)
c++ way
#include <string>
#include <math.h>
#include <iostream>
using namespace std;
int main() {
std::string stringNumber = "101110111";
long long result = 0;
uint string_length = stringNumber.length();
for(int i = 0; i <string_length; i++) {
if(stringNumber[i]=='1')
{
long pose_value = pow(2, string_length-1-i);
result += pose_value;
}
}
std::cout << result << std::endl;
}

C++: about precision of calculating (code is inside)

Can you give me advice about precision of computing Taylor series for an exponent? We have a degree of exponent and a figure of precision calculating as imput data. We should recieve a calculating number with a given precision as output data. I wrote a program, but when I calculate an answer and compare it with embedded function's answer, it has differents. Can you advice me, how I can destroy a difference between answeres? formula of exponent's calculating
#include "stdafx.h"
#include "iostream"
#include <math.h>
#include <Windows.h>
#include <stdlib.h>
using namespace std;
int Factorial(int n);
double Taylor(double x, int q);
int main()
{
double res = 0;
int q = 0;
double number = 0;
cout << "Enter positive number" << "\n";
cin >> number;
cout << "Enter rounding error (precision)" << "\n";
cin >> q;
cout << "\n" << "\n";
res = Taylor(number, q);
cout << "Answer by Taylor : " << res;
cout << "Answer by embedded function: " << exp(number);
Sleep(25000);
return 0;
}
int Factorial(int n) {
int res = 1;
int i = 2;
if (n == 1 || n == 0)
return 1;
else
{
while (i <= n)
{
res *= i;
i++;
}
return res;
}
}
double Taylor(double x, int q) {
double res = 1;
double res1 = 0;
int i =1;
while (i)
{
res += (pow(x, i) / Factorial(i));
if (int(res*pow(10, q)) < (res*pow(10, q)))
{//rounding res below
if ( ( int (res * pow(10,q+1)) - int(res*pow(10, q))) <5 )
res1 = (int(res*pow(10, q))) * pow(10, (-q));
else
res1 = (int(res*pow(10, q))) * pow(10, (-q)) + pow(10,-q);
return res1;
}
i++;
}
}
There are two problems in your code. First, the factorial is very prone to overflow. Actually I dont know when overflow occurs for int factorials, but I remember that eg on usual pocket calculators x! overflows already for x==70. You probably dont need that high factorials, but still it is better to avoid that problem right from the start. If you look at the correction that needs to be added in each step: x^i / i! (maths notation) then you notice that this value is actually much smaller than x^i or i! respectively. Also you can calculate the value easily from the previous one by simply multiplying it by x/i.
Second, I dont understand your calculations for the precision. Maybe it is correct, but to be honest for me it looks too complicated to even try to understand it ;).
Here is how you can get the correct value:
#include <iostream>
#include <cmath>
struct taylor_result {
int iterations;
double value;
taylor_result() : iterations(0),value(0) {}
};
taylor_result taylor(double x,double eps = 1e-8){
taylor_result res;
double accu = 1; // calculate only the correction
// but not its individual terms
while(accu > eps){
res.value += accu;
res.iterations++;
accu *= (x / (res.iterations));
}
return res;
}
int main() {
std::cout << taylor(3.0).value << "\n";
std::cout << exp(3.0) << "\n";
}
Note that I used a struct to return the result, as you should pay attention to the number of iterations needed.
PS: see here for a modified code that lets you use a already calculated result to continue the series for better precision. Imho a nice solution should also provide a way to set a limit for the number of iterations, but this I leave for you to implement ;)

Printing correct number of decimal points using %f c++

I am trying to print a number up to say 5 decimal places.
I have:
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
float a = 987.65;
float b = 1.23456789;
scanf("%f %f", &a, &b);
printf("%.5f %.5f", a, b);
return 0;
}
I get the result as 987.65000 and 1.23456
I want the result to be 987.65 and 1.23456, so basically I want up to 5 i.e <=5 decimal digits in my answer.
A slightly less technical way to do it would be using setprecision, as displayed below:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float a = 987.65;
float b = 1.23456789;
cout << setprecision(5);
cout << a << " " << b << endl;
return 0;
}
Output:
987.65 1.2346
The fundamental problem is that a computer can't exactly represent most floating point numbers.
Also, you want a complex formatting rule: if ending digits are zero, print spaces.
The problem is that your number 987.65000 could be represented as 98.6500001 and so wouldn't work with your formatting rule.
I believe you will have to write your own formatting function to achieve the functionality you are looking for.
Here's a solution that does what you want:
#include <iostream>
#include <cstdio>
using namespace std;
unsigned int numPlaces = 5; //number of decimal places
unsigned int determinePlaces (float number) {
unsigned int myPlaces = 0;
while (number != (int)(number) && myPlaces<=numPlaces-1) {
number = number*10;
myPlaces++;
}
return myPlaces;
}
int main() {
float a = 987.65;
float b = 1.23456789;
printf("%.*f %.*f\n", determinePlaces(a), a, determinePlaces(b), b);
return 0;
}
Output:
987.65 1.23457
Basically, the code keeps on multiplying the goat by 10 until the cast to an integer (essentially taking the floor value) matches the float. If it doesn't when it reaches the fifth multiplication by 10, we satisfy ourselves with a printf of 5 decimal places. Otherwise, we print the amount that was necessary to make the match to the floor value.

C++ Difference between the sum of the squares of the first ten natural numbers and the square of the sum

i wrote a code that calculates and outputs a difference between the sum of the squares of the first ten natural numbers and the square of the sum.
The problem is with function squareOfSum(). The function should return 3025 but it always returns 3024. Even if i try to put 100 into brackets i get 25502499 (25502500 is correct). No matter what number i put into brackets i always get the same problem.
What am I doing wrong?
Here's a screenshot of my output.
#include <iostream>
#include <cmath>
using namespace std;
int sumOfSquares(int limit);
int squareOfSum(int limit);
int main()
{
cout << sumOfSquares(10) << endl;
cout << squareOfSum(10) << endl;
cout << squareOfSum(10) - sumOfSquares(10) << endl;
}
int sumOfSquares(int limit)
{
int sum = 0;
for(int i = 1; i<=limit; i++)
{
sum +=pow(i,2);
}
return sum;
}
int squareOfSum(int limit)
{
int sum = 0, square = 0;
for(int i = 1; i<=limit; i++)
{
sum +=i;
}
square = pow(sum,2);
return square;
}
Note that pow is a function that works with floating point numbers. Optimizations might lead to rounding errors or truncation during implicit coversion to int. Replace pow(i, 2) with i*i and you'll get pure integer arithmetic and thus exact results.
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
int main()
{
int higher_limit = 100;
int SquaresOfSum = 0;
int SumOfSquares = 0,count=0;
for(int i=1;i<=higher_limit;i++){
count += i;
SumOfSquares += pow(i,2);
}
SquaresOfSum = pow(count,2);
cout<<SquaresOfSum-SumOfSquares;
}
Using Javascript
const sumSquareDifference = (n) => {
const numbers = [...Array(n + 1).keys()];
const sumOfSquares = numbers.reduce((accumulator, number) => accumulator + (number ** 2));
const squareOfSum = numbers.reduce((accumulator, number) => accumulator + number) ** 2;
return squareOfSum - sumOfSquares;
}
console.log(sumSquareDifference(10));