I saw a fun math problem on reddit the other day.

find a number n, so that sin(n)=-1, where n is an integer in radians; so sin(270 degrees) doesn’t count. Obviously it will never be exactly -1 but close enough for the difference to be lost in rounding.

I need the argument of sin function to be as close to an integer as possible. Call this integer m.

Solving for leads to:

If I have a rational approximation to with an even numerator I can divide it by two get my m. I also have to make sure that the denominator is in the form of 4n+3.

It’s possible to use continued fractions to approximate real numbers. Here’s a continued fraction sequence for pi: https://oeis.org/A001203

The first rational approximation I learned in elementary school is 22/7 which is perfect.

> (sin 11)

-.9999902065507035

For the others I’ll have to evaluate the continued fraction to get my approximation of a simple fraction.

> (eval-terms (list 3 7 15 1 292 1))

104348/33215

> (sin (/ 104348 2))

-.9999999999848337

> (eval-terms (list 3 7 15 1 292 1 1 1 2 1 3 1 14 2 1))

245850922/78256779

> (sin (/ 245850922 2))

-.99999999999999999532

Looks like a good candidate was found.

This is the code to evaluate a continued fraction coefficients. It’s very convenient that scheme has a native rational data type.

1 2 3 4 5 6 7 8 9 10 11 12 |
(define (eval-terms ts) (cond ((= (length ts) 1) (car ts)) (else (+ (car ts) (/ 1 (eval-terms (cdr ts))))))) (define (eval-terms-iter ts) (let ((rev-ts (reverse ts))) (define (ev-terms ts frac) (if (null? ts) frac (ev-terms (cdr ts) (+ (car ts) (/ 1 frac))))) (ev-terms rev-ts (car rev-ts)))) |

Given these two facts, we can come up with an algorithm to recover any rational number p/q, not just those between 0 and 1, by applying the general algorithm for guessing arbitrary integers n one at a time to recover all of the coefficients in the continued fraction for p/q. For now, though, we’ll just worry about numbers in the range (0, 1], since the logic for handling arbitrary rational numbers can be done easily given this as a subroutine.