yamaton's blog

By yamaton, history, 11 years ago, In English

EDIT2:

  • I was wrong, and the test cases were correct.

  • Added a section discussing my errors.

EDIT1:

  • Changed the threshold of Taylor series from to (thanks to Swistakk)

  • Fixed use of Fraction in Python: Fraction(str) instead of Fraction(float)

  • No change in the outcome.


TL;DR

600D - Area of Two Circles' Intersection requires careful treatment of loss of significance, more than the geometry itself. The test is plagued by the numerical errors, and rejects "more accurate" solution. EDIT2: Solving this problem with double precision turned out very hard!

Geometry

Let's review the geometry, first. We need three numbers (r1, r2, d); where d is the distance between two centers,

When two circles do not intersect, which is the case d ≥ r1 + r2, the area of intersection is zero.

When one circle is contained in the other, which is the case max(r1, r2) ≥ d + min(r1, r2), the intersection equals to the smaller circle.

Otherwise, intersection of two circles is determined from two circular sectors subtracted by two triangles, yielding

where angles θ1 and θ2 are determined from the cosine formula

So far, so good. I wrote Python code (with double representation), and failed. Rewrote in C++ using long double, and succeeded. But..., what was wrong?

Loss of significance

The culprit is loss of significance (wikipedia). It occurs when you take difference (y - x) of two close numbers x ≈ y. For example,

1.0023 - 1.0019 = 0.0004

The difference has only one significant digit although you started with numbers of five significant digits!

This type of numerical error can happen in two parts. One in inside of , the other in the function (θ - sinθ cos θ ) when θ is small .

Inside of the is just arithmetic operations so we can represent numbers as Fractions to avoid the error. (d is a floating point number but I still convert it into a fraction as well.)

(θ - sinθ cos θ ) involves non-arithmetic operation, so I use Taylor expansion. Wolfram|Alpha tells me like this.

The first three terms are good enough. I replaced the function f(x) with this form when ( EDIT1: changed the threshold to 0.01.)

Am I wrong, or test is wrong?

Here is my Python implementation.

"""
Codeforces Educational Round #2
Problem 600 D. Area of Two Circles' Intersection

@author yamaton
@date 2015-11-30
      2015-12-02
"""

import math
import fractions


def f(x):
    """
    compute  x - sin(x) cos(x) 
    without loss of significance
    """
    cos = math.cos
    sin = math.sin

    if abs(x) < 0.01:
        return 2 * x**3 / 3 - 2 * x**5 / 15 + 4 * x**7 / 315
    return x - sin(x) * cos(x)


def solve(r1, r2, d):
    acos = math.acos

    r1, r2 = min(r1, r2), max(r1, r2)
    if d >= r1 + r2:  # circles are far apart
        return 0.0     
    if r2 >= d + r1:  # whole circle is contained in the other
        return math.pi * r1 ** 2

    # Convert numbers into fractions before calculation.
    # Numbers are fractions until `acos()` is applied.
    df = fractions.Fraction("%.20f" % d)
    r1f, r2f = map(fractions.Fraction, [r1, r2])
    r1sq, r2sq, dsq = map(lambda i: i * i, [r1f, r2f, df])
    theta1 = acos((r1sq + dsq - r2sq) / (2 * r1f * df))
    theta2 = acos((r2sq + dsq - r1sq) / (2 * r2f * df))

    return r1 * r1 * f(theta1) + r2 * r2 * f(theta2)


def main():
    x1, y1, r1 = map(int, input().split())
    x2, y2, r2 = map(int, input().split())
    d = math.hypot(x1-x2, y1-y2)
    result = solve(r1, r2, d)
    print("%.20f" % result)


if __name__ == '__main__':
    main()

But this STILL fails on test 36. Here is a screenshot.

Am I wrong? Or, the test is wrong?

 →  ... It turned out I was wrong.

My Errors

I had two errors.

  1. d was computed first as hypotenuse, but the double value was insufficient in significance.

  2. acos returns inaccurate value when the argument is close to 1. According to Wikipedia,

For angles near 0 and π, arccosine is ill-conditioned and will thus calculate the angle with reduced accuracy in a computer implementation (due to the limited number of digits).

To fix them, I computed θ by keeping exact representation with fractions from scratch,

where σ1 is the sign (1 or -1) of r12 + d2 - r22. Also acos(sigma * sqrt(x)) part is computed with series when abs(x) is close to 1.

This is how I finally got AC with double precision: 14663921.

Lesson Learned:

  • Just use C++/Java so we can use long double or BigDecimal
  • Vote: I like it
  • +30
  • Vote: I do not like it

»
11 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by yamaton (previous revision, new revision, compare).

»
11 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by yamaton (previous revision, new revision, compare).

»
11 years ago, hide # |
Rev. 2  
Vote: I like it +14 Vote: I do not like it

I didn't investigate it in details, but I think that probably where loss of precision happens is calculating acos or computing f when x is not that small (however that shouldn't be that big :/...). You're right that loss of significance happens when we are subtracting two bigger numbers and get result of much smaller order, however some loss always happens when doing floating point operations and I believe that jury's output is right since many people got it ACed. And I'm probably not the best guy to inquire into this, however I guess that nobody likes caring about precision :P.

There were people who implemented it on BigDecimal, you can check their outputs, they should be very precise.

  • »
    »
    11 years ago, hide # ^ |
     
    Vote: I like it 0 Vote: I do not like it

    Thank you for your feedback (this was my first blog post!). I agree acos() might be source of error. Yes, I'll read the ACed code and hopefully update the post soon.

»
11 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Here are a few values for you to check with up to 40 digits precision:

df = 9.999999999999839209999999998707328795 * 10^8
theta1 = 2.196292330269372656062527289740493872 * 10^(-7)
theta2 = 1.464194886846241897711244415008671269749 * 10^(-7)
f(x) = x - sin(x) cos(x)
f(theta1) = 7.062836875680284549094681212158565232416 * 10^(-21)
f(theta2) = 2.092692407608956375531146423493114593979 * 10^(-21)
result = 0.001883423166848069823046361706402891691019
  • »
    »
    11 years ago, hide # ^ |
     
    Vote: I like it 0 Vote: I do not like it

    I really appreciate your values of Test #36. I used Mathematica and obtained exactly the same result as yours. Test was correct, and I was wrong!