I am trying to get random numbers between 10 and 20 with decimals, first I take the integer part and then the decimal part, this so that the probabilities of the integer part have a greater possibility of varying, and then the decimal part, but when adding the two parts begins to be rounded, I don't want it to be rounded because I want to get an exact number of decimal places, in this case 7 decimal places.
#include<iostream>
#include<math.h>
double random_decimal(int inicio, int fin, int numero_decimales)
{
double int_part = (rand() % (inicio + 1 - fin) + inicio);
int num = pow(10, numero_decimales);
double decimal_part = (double)(rand() % (1 - num)) / num;
cout << "Int: "<< int_part << " Dec: "<< decimal_part << " Sum: "<< int_part + decimal_part << endl;
return (double)(int_part + decimal_part);
}
int main()
{
int ed;
double ps, estat;
for(int i = 0; i < 10; i++)
{
double x = random_decimal(10, 20, 7);
}
}
For starters, don't use rand() if you can use one of the C++11 random classes instead: https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful
For example:
std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(10.0,20.0);
As far as "rounding" or "exact number of decimal places" - I wouldn't worry about that. Specifically:
https://peter.bloomfield.online/decimal-places-in-a-floating-point-number/
Significant figures != decimal places
It’s easy to make the mistake of thinking that the code above answers
our decimal places question. However, consider the following numbers:
0.12345123451234512345
0.00000000000000012345
Both of them are written with 20 decimal places. However, the second
one would only require 5 significant figures (or the equivalent of 5
decimal digits in the mantissa). The extra leading zeroes after the
decimal point can be represented by simply decreasing the exponent
(i.e. making it more negative), leaving the entire mantissa available
for precision.
Read the rest of the article for more details. But I suspect "rounding" (as I think you're using the term) probably isn't an issue for your particular application.
Your numbers are only being rounded when you are printing them:
$ cat que.cpp
#include <iomanip>
#include <iostream>
#include <math.h>
using namespace std;
double random_decimal(int inicio, int fin, int numero_decimales) {
double int_part = (rand() % (inicio + 1 - fin) + inicio);
int num = pow(10, numero_decimales);
double decimal_part = (double)(rand() % (1 - num)) / num;
cout << setprecision(numero_decimales) << fixed;
cout << "Int: " << int_part << " Dec: " << decimal_part
<< " Sum: " << int_part + decimal_part << endl;
return (double)(int_part + decimal_part);
}
int main() {
int ed;
double ps, estat;
for (int i = 0; i < 10; i++) {
double x = random_decimal(10, 20, 7);
}
}
$ g++ -o que que.cpp && ./que
Int: 11.0000000 Dec: 0.6930970 Sum: 11.6930970
Int: 10.0000000 Dec: 0.4637086 Sum: 10.4637086
Int: 15.0000000 Dec: 0.4238377 Sum: 15.4238377
Int: 11.0000000 Dec: 0.9760656 Sum: 11.9760656
Int: 16.0000000 Dec: 0.9641539 Sum: 16.9641539
Int: 15.0000000 Dec: 0.0490162 Sum: 15.0490162
Int: 15.0000000 Dec: 0.2520169 Sum: 15.2520169
Int: 15.0000000 Dec: 0.7514122 Sum: 15.7514122
Int: 16.0000000 Dec: 0.0383580 Sum: 16.0383580
Int: 17.0000000 Dec: 0.3455866 Sum: 17.3455866
Related
I want to get square root of a number upto 9 precision points so I did something like below but I am not getting correct precision. Here e is the precision which is greater than 10^9 then also ans is upto 5 precision points. What am I doing wrong here??
#include <iostream>
using namespace std;
long double squareRoot(long double n)
{
long double x = n;
long double y = 1;
long double e = 0.00000000000001;
while (x - y > e)
{
x = (x + y) / 2;
y = n / x;
}
cout << x << "\n";
return x;
}
int main()
{
int arr[] = {2,3,4,5,6};
int size = sizeof(arr)/sizeof(arr[0]);
long double ans = 0.0;
for(int i=0; i<size; i++)
{
ans += squareRoot(arr[i]);
}
cout << ans << "\n";
return 0;
}
The output is
1.41421
1.73205
2
2.23607
2.44949
9.83182
What should I do to get precision upto 9 points??
There are two places at which precision plays a role:
precision of the value itself
precision of the output stream
You can only get output in desired precision if both value and stream are precise enough.
In your case, the calculated value doesn't seem to be a problem, however, default stream precision is only five digits, i. e. no matter how precise your double value actually is, the stream will stop after five digits, rounding the last one appropriately. So you'll need to increase stream precision up to the desired nine digits:
std::cout << std::setprecision(9);
// or alternatively:
std::cout.precision(9);
Precision is kept until a new one is set, in contrast to e. g. std::setw, which only applies for next value.
try this
cout << setprecision(10) << x << "\n";
cout << setprecision(10) << ans << "\n";
I'm having a problem with the following simple code, I don't know why the output will become negative... The program is supposed to calculate the sum of all odd and five-digit numbers like 10001, 10003, 10005, etc.
#include <iostream>
using namespace std;
int main()
{
int num, sum = 0;
for (num = 10001 ; num <= 99999 ; num+=2){
sum += num;
}
cout << num << " " << sum;
return 0;
}
It means that there is an overflow of type int. That is this type can not represent the sum. I advice to declare variable sum like
long long int sum = 0;
After that you can compare the result with the maximum value stored in type int. For example
#include <limits>
//...
std::cout << std::numeric_limits<int>::max() << " " << sum << std::endl;;
Your int will likely overflow. Switch it to long
int num = 0;
long long sum = 0L;
Assuming you have a 4 byte int, the maximum value will be 2^31 - 1 == 2147483647. See this example
Your sum will come out to 2475000000 which will overflow.
I am having trouble rounding a GPA double to 2 decimal places. (ex of a GPA needed to be rounded: 3.67924) I am currently using ceil to round up, but it currently outputs it as a whole number (368)
here is what I have right now
if (cin >> gpa) {
if (gpa >= 0 && gpa <= 5) {
// valid number
gpa = ceil(gpa * 100);
break;
} else {
cout << "Please enter a valid GPA (0.00 - 5.00)" << endl;
cout << "GPA: ";
}
}
using the above code with 3.67924 would output 368 (which is what I want, but just without the period between the whole number and the decimals). How can I fix this?
To round a double up to 2 decimal places, you can use:
#include <iostream>
#include <cmath>
int main() {
double value = 0.123;
value = std::ceil(value * 100.0) / 100.0;
std::cout << value << std::endl; // prints 0.13
return 0;
}
To round up to n decimal places, you can use:
double round_up(double value, int decimal_places) {
const double multiplier = std::pow(10.0, decimal_places);
return std::ceil(value * multiplier) / multiplier;
}
This method won't be particularly fast, if performance becomes an issue you may need another solution.
If it is just a matter of writing to screen then to round the number use
std::cout.precision(3);
std::cout << gpa << std::endl;
see
floating points are not exactly represented so by internally rounding the value and then using that in your calculations you are increasing the inexactness.
When you are trying to store values upto n decimal values in a variable .
You have to multiple that value with 10^n and divide the same with 10^n.
Afterward use type operator to manipulate in the program.
Here is the example : -
float a,b,c,d,sum;
cin>>a>>b>>c>>d; // reading decimal values
sum=(a*b*c*d);
sum=round(sum*100)/100; // here it is for 2 decimal points
if((float)sum < (float) 9.58)
cout<<"YES\n";
else
cout<<"NO\n";
You can't round doubles to two decimal places. Doubles don't have decimal places. They have binary places, and they aren't commensurable with decimal places.
If you want decimal places, you must use a decimal radix, e.g. when formatting for output with printf("%.2f", ...).
Try this. But your cout statement in else condition, so it won't give the desired output for 3.67924.
if (cin >> gpa)
{
if (gpa >= 0 && gpa <= 5) {
// valid number
gpa = ceil(gpa * 100);
gpa=gpa/100;
break;
}
else
{
cout << "Please enter a valid GPA (0.00 - 5.00)" << endl;
cout << "GPA: ";
}
}
Example: you want 56.899999999999 to be output as a string with 2 decimal point which is 56.89.
First, convert them
value = 56.89 * 1000 = 5689
factor = 100
- 1 decimal point = 10
- 2 decimal point = 100
- 3 decimal point = 1000
etc
int integerValue;
int decimal;
std::string result;
function ( int value , int factor)
{
integerValue= (value / factor) * factor; //(5689 / 100) * 100 = 5600
decimal = value - integerValue; // 5689 - 5600;
result = std::to_string((int)(value/factor) + "." + std::to_string(decimal);
// result = "56" + "." + "89"
// lastly, print result
}
Not sure if this can help?
std::string precision_2(float number)
{
int decimal_part = (number * 100) - ((int)number * 100);
if (decimal_part > 10) {
return std::to_string((int)number) + "." + std::to_string(decimal_part);
} else {
return std::to_string((int)number) + ".0" + std::to_string(decimal_part);
}
}
Handles well for all positive floats. A minor modification will make it work for -ves as well.
I am trying to write two loops in one for loop so I looked up the syntax for multiple variables in the for loop
the problem is the second variable l isn't updating I don't know why
#include<iostream>
using namespace std;
int main ()
{
float vsum=0, lsum=0;
double nsum=0, msum=0;
float v=1, l=100000000;
for (v, l ; v<= 100000000, l >= 1 ; v++, l--)
{
vsum= vsum + 1/v;
nsum= nsum + 1/v;
lsum= lsum + 1/l;
msum= msum+ 1/l;
}
cout << " The float sum of all numbers 1 through 1/100000000 is " << vsum << endl;
cout << " The double sum of all numbers 1 through 1/100000000 is " << nsum << endl;
cout << "The float sum of all numbers 1/100000000 through 1/1 is " << lsum << endl;
cout << "The double sum of all numbers 1/100000000 through 1/1 is " << msum << endl;
cin >> vsum;
}
I guess your question is that after
float f = 100000000;
why does --f; leave f unchanged?
The answer is due to the granularity of float. The float does not have enough accuracy to store every possible integer. Clearly a 32-bit float cannot store as many integer values as a 32-bit int, for example.
The further away from 0 you get, the larger the gap gets between successive possible values of a float. On your system 100000000 - 1 is still larger than the next possible value of float below 100000000.
The rules of C++ are that when the result of the calculation is not representable exactly by a float, then it's implementation-defined whether the next-lowest value or the next-highest value is used. (So your compiler should actually document what happens here). In this case your system is using the next-highest value.
To get your intended results, make v and l be integral types, and do a float conversion in the actual calculation, e.g.
vsum += 1.f/v;
nsum += 1.0/v;
As dasblinkenlight mentions, you are only checking the second condition, but the second variable is updating just fine. Here is an abridged example that proves this.
#include<iostream>
using namespace std;
int main ()
{
float vsum=0, lsum=0;
double nsum=0, msum=0;
float v=1, l=10;
for (v, l ; v<= 10, l >= 1 ; v++, l--)
{
cout << v << " " << l << endl;
}
}
Output:
1 10
2 9
3 8
4 7
5 6
6 5
7 4
8 3
9 2
10 1
My goal is to add the value in front of my decimal place when the first decimal places is more than or equal to 5.
For example:
#include <iostream>
using namespace std;
int main()
{
float num = 0.5222f;
cout << (int)num << endl;
cin.get();
return 0;
}
My intended result is 1 instead of 0. How should I modify the code to get the expected result?
If you want to round this value to the nearest integer, you could just add 0.5 before casting it to int:
float num = 0.5222f;
cout << (int)(num + 0.5);
or alternatively you might use one of the following functions from the <cmath> header:
double round (double x);
float roundf (float x);
long double roundl (long double x);
In C++11 we now have std::round, so this would work fine:
std::cout << std::round(num) << std::endl;
would also need to include <cmath>. The non-C++11 method using floor:
std::cout << floor(num + 0.5) << std::endl;
If you cast a float to an int it rounds towards zero, dropping the fractional portion of the number.
What you want to do is call roundf first. (round for double, roundf for float)
cout << (int)roundf(num) << endl;
I just add:
float num = 0.5222f;
cout << std::floor(num + 0.5);
In this way you can even decide to round up also if (say) first digit is > 3
float num = 0.3222f;
cout << std::floor(num + 0.7);
Don't know how much useful, but.... you can!
Try the ceil function.
It rounds up numbers of 0.5 to a whole decimal number by 1.
http://en.cppreference.com/w/cpp/numeric/math/ceil