从零开始构建Nix三角函数数学库
Nix Trigonometric Math Library from Ground Zero

原始链接: https://lantian.pub/en/article/modify-computer/nix-trigonometric-math-library-from-zero.lantian/

作者旨在通过计算17个虚拟专用服务器(VPS)节点之间的延迟来优化网络路由,这些节点的地理位置各不相同。手动 ping 测试效率太低,因此作者选择使用 Haversine 公式根据经纬度计算距离。然而,Nix 系统缺乏原生三角函数,最初依靠 Python 的 `geopy` 模块进行距离计算。这种方法速度很慢(每对节点 0.5 秒)且无法并行化。 为了克服这些限制,作者着手创建一个纯 Nix 三角数学库。他们使用泰勒展开式实现了 `sin`、`cos` 和 `tan` 函数,并仔细控制精度和收敛性。`arctan` 函数为了速度采用了多项式回归近似。`sqrt` 函数使用牛顿法实现。这些函数都经过了严格的精度测试(误差小于真实值的 0.0001%)。最终,Haversine 公式得以实现,从而能够计算距离,并随后根据光速估算网络延迟。最终的 Nix 库已上传至 GitHub。

Hacker News 最新 | 往期 | 评论 | 提问 | 展示 | 招聘 | 提交 登录 从零开始构建 Nix 三角函数数学库 (lantian.pub) 8 分,来自 todsacerdoti,2 小时前 | 隐藏 | 往期 | 收藏 | 讨论 加入我们,参加 6 月 16-17 日在旧金山举行的 AI 初创公司学校! 指导原则 | 常见问题 | 列表 | API | 安全 | 法律 | 申请 YC | 联系我们 搜索:

原文

(Title image sourced from: Wikipedia - Trigonometry)

Why

I wanted to calculate the network latency between all my VPS nodes, and add the latency into the configuration file of Bird BGP daemon, so the network packets are forwarded through the lowest latency route. However, I have 17 nodes as of today, and I didn't want to manually run a ping command between each pair.

So I came up with a solution: I can mark the latitudes and longitudes of the physical locations of my nodes, calculate the physical distance, and divide that by half the light speed to get the approximate latencies. I randomly sampled a few node pairs, and found that the Internet routing between them are mostly straightforward, with no significant detours. In this case, the physical distance is a good approximation that satisfies my requirements.

Because I use NixOS across all my nodes, and manage all configs with Nix, I need to find a way to calculate this distance with Nix. One commonly used method to calculate distance based on latitude/longitude is Haversine formula. It approximates the Earth as a sphere with a radius of 6371km, and then use the following formula to calculate the distance:

Reference: Wikipedia - Haversine formula

h=hav(dr)=(hav(φ2φ1)+cos(φ1)cos(φ2)hav(λ2λ1))Where: hav(θ)=sin2(θ2)=1cos(θ)2Therefore: d=rarchav(h)=2rarcsin(h)=2rarcsin(sin2(φ2φ12)+cos(φ1)cos(φ2)sin2(λ2λ12))\begin{aligned} h = hav(\frac{d}{r}) &= (hav(\varphi_2 - \varphi_1) + \cos(\varphi_1) \cos(\varphi_2) hav(\lambda_2 - \lambda_1)) \\ \text{Where: } hav(\theta) &= \sin^2(\frac{\theta}{2}) = \frac{1 - \cos(\theta)}{2} \\ \text{Therefore: } d &= r \cdot archav(h) = 2r \cdot arcsin(\sqrt{h}) \\ &= 2r \cdot \arcsin(\sqrt{\sin^2 (\frac{\varphi_2 - \varphi_1}{2}) + \cos(\varphi_1) \cos(\varphi_2) \sin^2 (\frac{\lambda_2 - \lambda_1}{2})}) \end{aligned}
联系我们 contact @ memedata.com