I am very confused about when I should use double and when I should use long double.
In yesterdays educational round, my solution for 1009C - Надоевший подарок has failed for using double. After system testing, I resubmitted it using long double and it got accepted.
My solution using double got WA on test 39: 40379060
My same code replacing double with long double got accepted: 40379089
Update:
When I use long long tot
for storing the sum of all calculation and finally used double ans = tot*1.0/n
it also got accepted: 40379501 ! Why ?? Then why WA when using double tot
? Since the sum of all calculation don't have any precision or floating point value, precision is coming only when dividing by n, then why using double gave WA ?
As far as I know double can store value up to 1.8×10308 (approximately). So, why long double is needed here? Isn't double is enough here?
Also, during contest or online problem solving how should I decide which one I should use: double or long double?
Is it safe to use long double always for all problems? Or is there any specific case when I should use long double ?
Thanks in advance.
I don't think that problem is with double,mine solution pass with using double.May be you have not used appropriate precision.
From C++ Primer, 5e
From my experience, you should never use long double. It's slower and completely useless since double precision is always enough if you are careful enough. You probably have some precision issue here.
UPD: Oh, I see now why you got WA.
Since the sum of all calculation don't have any precision or floating point value, precision is coming only when dividing by n
That statement is very far from true. Precision in floating type comes not from numbers after floating point — precision exists because number of meaningful digits that can be stored in double is limited. You can store numbers up to 10308 because double also stores power of 10 separately.
double tot
stores numbers up to 1018 in your problem, and it simply can't store all of ~64 digits that can exists, so there goes significan't precision issue. Yeah, on of the way to dodje this is to use long double.Rule 1 of floating point numbers — don't use floating point numbers.
Only place in this task that requires floating point calculations is division by n at the end.
Here is a AC solution using float http://mirror.codeforces.com/contest/1009/submission/40386856.
Have you read his post? He already wrote solution without float numbers... He just don't understand how precision works.