feat: Add Liu Hui's π algorithm (#61)

This commit is contained in:
mantou 2018-06-12 19:54:00 +08:00 committed by Oleksii Trekhleb
parent bc17e4ea2c
commit 7dc9b80f62
4 changed files with 79 additions and 0 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
node_modules node_modules
.idea .idea
coverage coverage
.vscode

View File

@ -0,0 +1,9 @@
# Liu Hui's π Algorithm
Multiply one side of a hexagon by the radius (of its circumcircle), then multiply this by three, to yield the area of a dodecagon; if we cut a hexagon into a dodecagon, multiply its side by its radius, then again multiply by six, we get the area of a 24-gon; the finer we cut, the smaller the loss with respect to the area of circle, thus with further cut after cut, the area of the resulting polygon will coincide and become one with the circle; there will be no loss
## References
- [Liu Hui's π Algorithm on Wikipedia](https://en.wikipedia.org/wiki/Liu_Hui's_%CF%80_algorithm)

View File

@ -0,0 +1,16 @@
import pi from '../liu-hui-pi';
describe('Liu Hui\'s π algorithm', () => {
it('Dodecagon π', () => {
expect(pi(1)).toBe(3);
});
it('24-gon π', () => {
expect(pi(2)).toBe(3.105828541230249);
});
it('6144-gon π', () => {
expect(pi(10)).toBe(3.1415921059992717);
});
it('201326592-gon π', () => {
expect(pi(25)).toBe(3.141592653589793);
});
});

View File

@ -0,0 +1,53 @@
// Liu Hui began with an inscribed hexagon.
// Let r is the radius of circle.
// r is also the side length of the inscribed hexagon
const c = 6;
const r = 0.5;
const getSideLength = (sideLength, count) => {
if (count <= 0) return sideLength;
const m = sideLength / 2;
// Liu Hui used the Gou Gu theorem repetitively.
const g = Math.sqrt((r ** 2) - (m ** 2));
const j = r - g;
return getSideLength(Math.sqrt((j ** 2) + (m ** 2)), count - 1);
};
const getSideCount = splitCount => c * (splitCount ? 2 ** splitCount : 1);
/**
* Calculate the π value using Liu Hui's π algorithm
*
* Liu Hui argued:
* Multiply one side of a hexagon by the radius (of its circumcircle),
* then multiply this by three, to yield the area of a dodecagon; if we
* cut a hexagon into a dodecagon, multiply its side by its radius, then
* again multiply by six, we get the area of a 24-gon; the finer we cut,
* the smaller the loss with respect to the area of circle, thus with
* further cut after cut, the area of the resulting polygon will coincide
* and become one with the circle; there will be no loss
* @param {Number} splitCount repeat times
* @return {Number}
*/
const pi = (splitCount = 1) => {
const sideLength = getSideLength(r, splitCount - 1);
const sideCount = getSideCount(splitCount - 1);
const p = sideLength * sideCount;
const area = (p / 2) * r;
return area / (r ** 2);
};
// !test
// for (let i = 1; i < 26; i += 1) {
// const p = pi(i);
// console.log(
// 'split count: %f, side count: %f, π: %f, is Math.PI? %o',
// i,
// getSideCount(i),
// p,
// p === Math.PI,
// );
// }
export default pi;