Need to improve sqrt precision

For a problem I'm doing, my answer must be accurate to 10-6.

Part of the program finds the square root of a number using sqrt(). The answer is not precise enough though.

Is there any way to improve the precision of sqrt()?
Last edited on
Use double instead of float.
Already doing that. Am I doing something else wrong? At the moment my code looks like this:

double hyp = sqrt(opp*opp + adj*adj);
Last edited on
I don't see anything wrong. Using long double instead of double might work better.
Last edited on
¿what's the relative precision that you need?

Maybe your approach is wrong, ¿what's the problem?
Sorry, no change.

Do you want to check the full code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<iostream>
#include<cmath>

using namespace std;

//http://codeforces.com/contest/190/problem/B

int main()
{
	
	int x[2], y[2], r[2];
	
	for(int i=0; i < 2; i++)
		cin >> x[i] >> y[i] >> r[i];
	
	long double opp = (x[0] - x[1]);
	long double adj = (y[0] - y[1]);
	
		cout << "opp = " << opp << endl;
		cout << "adj = " << adj << endl;
	
	long double hyp = sqrt((opp*opp) + (adj*adj));
	
		cout << "hyp = " << hyp << endl;
	
	long double ans = (hyp - r[0] - r[1]) / 2.0;
	
		cout << "ans = " << ans << endl;


	return 0;
}
Last edited on
By precise enough, do you mean you just want to print more decimals?

If that's not it, can you please give an example with what input you use and what output you expect?
Maybe that's the problem! I thought that sqrt() was giving me a rounded number, but perhaps the problem is just the output.

Here is the example test case:

input:
-10 10 3
10 -10 3

output:
11.142135623730951


My output is only 11.421.

Can I simply print more decimals? How would I do that?
Last edited on
setprecision and fixed http://cplusplus.com/reference/iostream/manipulators/

However, your solution is incorrect.
Wait, no, I just mistyped. The actual answer I got was 11.1421. Sorry for any confusion.

Thanks for the link, I've submitted my solution and passed the test cases!
You just passed 6 of them.
Hint: you are outputting a negative radius
What I mean is that there isn't a major problem with the solution. I don't understand why the 7th test failed, but I'm going to have a go at fixing it.
Topic archived. No new replies allowed.