I was working on something else, but everything came out as zero, so I made this minimalistic example, and the output is still 0.
#include <iostream>
int main(int argc, char** argv)
{
double f=3/5;
std::cout << f;
return 0;
}
What am I missing?
You are missing the fact that 3 and 5 are integers, so you are getting integer division. To make the compiler perform floating point division, make one of them a real number:
double f = 3.0 / 5;
It doesn't need to be .0, you can also do 3./5 or 3/5. or 3e+0 / 5 or 3 / 5e-0 or 0xCp-2 / 5 or... There only needs to be an indicator involved so that the compiler knows it's supposed to perform the division as floating point.
Another possibility: double f=double(3)/5. That's much more typing, but it leaves no doubt to what you are doing.
Or simply use double f=.6, that also does the trick...
try this:
double f = 3.0/5.0;
this should fix your problem
Try putting a .0 after one of the divisors. This will convert them into floating point literals.
You are using integers. You can many things to make your constants double like leftaroundabout states, however that is not good clean good. It is hard to read and confusing. If you want 3 and 5 make them 3.0 and 5.0. Everyone will know what you mean if they are forced to read your code. Much of what he/she states really requires you to know C/C++ and how floats are storage to make heads or tails.
In case, you save your generic variables with int and would like to obtain the ratio as double:
using namespace std;
int main()
{
int x = 7;
int y = 4;
double ratio;
ratio = static_cast<double>(x)/static_cast<double>(y);
cout << "ratio =\t"<<ratio<< endl;
}
Related
I had an exercise in my book which made me to puzzle the answer by a long series of attempts which took me hours to configure out. I'm new to c++, and programming at all, which makes me lack of knowledge(actually I'm learning at home by the book). So i got a couple of questions which i hope you could answer them and "asset" my brains on the right place.
Before the questions, the exercise was :
"Write a random-number generator that returns a random floating point
number between 0.0 and 1.0. (Hint: Call rand, cast the result r to type
double by using static_cast(r), and then divide by the highest value
in the int range, RAND_MAX.) Make sure you declare the function with the
double return type.".
The questions:
what is the main function/idea that stands behind the srand(time(nullptr))?
I keep getting a warning of c4244 ('argument': conversion from 'time_t' to 'unsigned int'). I was searching the answer and I figured out the problem is in the srand command... please somebody can explain it?
I'm not truly clear about the static_cast and all the other 3 casting types . I know that in the static_cast i can define a new enum type from the parentheses to the braces from the left: static_cast<double>(r). But, what is the limit/definition of each cast(dynamic_cast, reinterpret_cast and const_cast)? When do i use them?
I figured out that i must declare a double before the (RAND_MAX) statement, but i have no idea why it must be double and not int or float? What is the main idea that stands behind the RAND_MAX?
This is the code that i wrote(note: I'm using #include "stdafx.h" pre header just in case of... while in the book there is nothing mentioned about it):
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
double rand_(int r);
int main() {
int n;
double r;
cout << " choose a number: ";
cin >> n;
srand(time(nullptr));
for (int i = 0; i <= n; i++) {
r = rand_(n) ;
cout << r << " ";
}
return 0;
}
double rand_(int r) {
static_cast<double>(r);
return rand() / double(RAND_MAX);
}
If you notice any "clearance" mistakes of basic coding please correct me.
Thanks for all who answer and support this post. Hope in future could do the same.
srand(time(nullptr));
its used to initialise pseudo random number generator, with seed, obtained from current time (to get different rundom numbers each time you run your ptogramm).
srand() accepts unisgned int parameter, time() return time_t, so here is your warning about conversion.
rand() / double(RAND_MAX)
rand() return integer value, RAND_MAX is integer constant, so to get floating point division, instead of integer division RAND_MAX is conversed to floating point type.
As for when to use which type of cast its bit to broad, and I'm pretty sure you can find info about every particular cast on SO or cppreference.
This question already has answers here:
Store and work with Big numbers in C
(3 answers)
Closed 6 years ago.
How to calclute 2 to the power 10000000 without crashing the compiler. What shoud be data type for extramily big integer in c/c++.
For the very specific value 2 raised to the power of 1000 a double is sufficient.
#include <stdio.h>
#include <math.h>
int main(int argc, const char *argv[]) {
printf("%f\n", pow(2., 1000));
return 0;
}
In general however you will need to implement an arbitrary precision multiplication algorithm to compute numbers that big (or use a library that provides that).
C++ has no predefined standard functions for this kind of computation.
If you want to implement your own version as an exercise then my suggestion is to use numbers in base 10000. They're small enough that single-digit multiplication won't overflow and it's very easy and fast to translate the result into decimal at the end because you can just map base-10000 digits to decimal without having to implement division an modulo too.
Also to compute such a big power (10,000,000) you will need to implement power by squaring, i.e.
BigNum pow(BigNum a, int b) {
if (b == 0) {
return 1;
} else if (b & 1) {
return a*pow(a, b-1);
} else {
BigNum x = pow(a, b/2);
return x*x;
}
}
this will allow to compute pow(a, b) with O(log(b)) instead of O(b) multiplications.
Store the digits in an int array where each location of the array denotes one digit. Then multiply them repetitively. That way you will get the answer with out crashing the compiler.
Well you need 302 locations for that. And the multiplication is simply the one that we do in grade classes. You have implement it in coding.
Little bit of code
int d[400];
for(int i=0;i<399;i++)
d[i]=0;
d[0]=1;
int carry=0;
int temp=0;
for(int j=0;j<=999;j++)
{
carry=0;
temp=0;
for(int i=0;i<=399;i++)
{
temp=d[i]*2+carry;
d[i]= temp%10;
carry = temp/10;
}
}
print d[0..399] in reverse order trimming zeroes.
Unlike Python/Java, C++ does not handle such big number by itself nor does it have a dedicated data type for it. You need to use an array to store the numbers. You do not have a data type for the problem. These kind of questions are common in competitive programming sites. Here is a detailed tutorial.
Large Number in C/C++
You can also learn about bit manipulation. They are handy when you multiply by 2.
Please read this before using pow(2., 1000) as mentioned in another answer.
c++ pow(2,1000) is normaly to big for double, but it's working. why?
As #6502 cleraly puts it in his answer, it can be used for this specific case of 2^1000. I missed that, be careful about that in case you are going to use this in a competitive programming site.
I need to remove digits after decimal points but not all.
For Example, double dig=3.1459038585 i need to convert it to dig=3.14
I think i need to multiple dig to 100 then convert it to integer and then again convert to double and delete to 100 (All this will be 1 line). But is there any function to do this faster?
Any function that implements this functionality will be more flexible, and as such slower by definition. So yes, just write this:
double truncated = (double)((int)dig*100)/100;
It's all CPU-native operations any way so it'll barely cost any clock cycles, especially if inlined or used as a macro.
#include <cmath>
#include <iostream>
int main()
{
double d = 3.1459038585;
std::cout << std::floor(d * 100.) / 100. << std::endl;
}
I'm teaching myself C++ and on this practice question it asks to write code that can calculate PI to >30 digits. I learned that double / long double are both 16 digits precise on my computer.
I think the lesson of this question is to be able to calculate precision beyond what is available. Therefore how do I do this? Is it possible?
my code for calculating Pi right now is
#include "stdafx.h"
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
int main(){
double pi;
pi = 4*atan(1.0);
cout<<setprecision(30)<<pi;
return 0;
}
Output is to 16 digits and pi to 30 digits is listed below for comparison.
3.1415926535897931
3.141592653589793238462643383279
Any suggestions for increasing precision or is this something that won't matter ever? Alternatively if there is another lesson you think I should be learning here feel free to offer it. Thank you!
You will need to perform the calculation using some other method than floating point. There are libraries for doing "long math" such as GMP.
If that's not what you're looking for, you can also write code to do this yourself. The simplest way is to just use a string, and store a digit per character. Do the math just like you would do if you did it by hand on paper. Adding numbers together is relatively easy, so is subtracting. Doing multiplication and division is a little harder.
For non-integer numbers, you'll need to make sure you line up the decimal point for add/subtract...
It's a good learning experience to write that, but don't expect it to be something you knock up in half an hour without much thought [add and subtract, perhaps!]
You can use quad math, builtin type __float128 and q/Q suffixes in GCC/clang.
#include <stdio.h>
#include <quadmath.h>
int main ()
{
__float128 x = strtoflt128("1234567891234567891234567891234566", nullptr);
auto y = 1.0q;
printf("%.Qf", x + y); // there is quadmath_snprintf, but this also works fine
return 0;
}
i have posted a few hours ago question about newtons method,i got answers and want to thanks everybody,now i have tried to implement code itself
#include <iostream>
#include <math.h>
using namespace std;
#define h powf(10,-7)
#define PI 180
float funct(float x){
return cos(x)-x;
}
float derivative (float x){
return (( funct(x+h)-funct(x-h))/(2*h));
}
int main(){
float tol=.001;
int N=3;
float p0=PI/4;
float p=0;
int i=1;
while(i<N){
p=p0-(float)funct(p0)/derivative(p0);
if ((p-p0)<tol){
cout<<p<<endl;
break;
}
i=i+1;
p0=p;
if (i>=N){
cout<<"solution not found "<<endl;
break;
}
}
return 0;
}
but i writes output "solution not found",in book after three iteration when n=3 ,it finds solution like this .7390851332,so my question is how small i should change h or how should i change my code such that,get correct answer?
Several things:
2 iterations is rarely going to be enough even in the best case.
You need to make sure your starting point is actually convergent.
Be aware of destructive cancellation in your derivative function. You are subtracting two numbers that are very close to each other so the difference will lose a lot of precision.
To expand on the last point, the general method is to decrease h as the value converges. But as I mentioned in your previous question, this "adjusting" h method essentially (algebraically) reduces to the Secant Method.
If you make h too small then your derivative will be innaccurate due to floating point roundoff. Your code would benefit from using double precision rather than single, especially as you are doing differentiation by finite difference. With double precision your value of h would be fine. If you stick to single precision you will need to use a larger value.
Only allowing 2 iterations seems rather restrictive. Make N larger and get your program to print out the number of iterations used.
Also, no need to use pow. Simply write 1e-7.
You're only allowing 2 iterations which may not be enough to get close enough to the answer. If you only have 1 correct bit to start, you can expect to have at best about 4 good bits after 2 iterations. You're looking for 10 bits accuracy (0.001 is roughly 1/2^10), you have to allow at least 2 more iterations.
Moreover, the quadratic convergence property only holds when you're close to the solution. When you're further out, it may take longer to get close to the solution.
The optimal h for computing the numerical derivative using central differences is 0.005 * max(1,|x|) for single-precision (float), where |x| is the absolute value of the argument, x. For double precision, it's about 5e-6 * max(1,|x|).