惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Threatpost
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
T
The Blog of Author Tim Ferriss
S
SegmentFault 最新的问题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 司徒正美
T
Tailwind CSS Blog
The Cloudflare Blog
The Last Watchdog
The Last Watchdog
PCI Perspectives
PCI Perspectives
博客园 - 聂微东
Stack Overflow Blog
Stack Overflow Blog
TaoSecurity Blog
TaoSecurity Blog
云风的 BLOG
云风的 BLOG
C
Cybersecurity and Infrastructure Security Agency CISA
O
OpenAI News
Recorded Future
Recorded Future
GbyAI
GbyAI
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Y
Y Combinator Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
量子位
博客园 - 叶小钗
V
Vulnerabilities – Threatpost
F
Full Disclosure
Recent Announcements
Recent Announcements
Vercel News
Vercel News
S
Schneier on Security
H
Heimdal Security Blog
Cisco Talos Blog
Cisco Talos Blog
V2EX - 技术
V2EX - 技术
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
B
Blog RSS Feed
宝玉的分享
宝玉的分享
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Privacy & Cybersecurity Law Blog
T
Threat Research - Cisco Blogs
G
Google Developers Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
爱范儿
爱范儿
IT之家
IT之家
大猫的无限游戏
大猫的无限游戏
C
Check Point Blog
N
Netflix TechBlog - Medium
S
Security @ Cisco Blogs
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Microsoft Azure Blog
Microsoft Azure Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Cyberwarzone
Cyberwarzone

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Floating-point will quietly corrupt your emissions math, and 0.1 + 0.2 already warned you
Jeremiah Say · 2026-05-23 · via DEV Community

Every developer has seen this:

0.1 + 0.2
// 0.30000000000000004

Enter fullscreen mode Exit fullscreen mode

It's the most-shared bug in programming. You learn it, you nod, you move on — because in most code the error is so far down the decimal that nothing notices. A pixel is off by a billionth. A timer fires a nanosecond late. Nobody files a ticket.

Then you build a system whose entire job is to add thousands of numbers together and produce a total that has to match a figure someone calculated by hand. And the rounding error you waved away in the tutorial becomes a line in an audit report that says: the system total does not reconcile to the source data.

That's where I met this bug for real, building the calculation layer at GreenCalculus.com. It runs over a thousand emissions calculators, and every one of them has the same hard requirement: the number the engine produces must reconcile, to the last reported digit, against the number a practitioner gets when they check the math themselves. "Close enough" is a finding. This post is the set of rules that get you from the math looks right to the math reconciles.


Why this bites harder in measurement code than anywhere else

Most software treats numbers as means to an end — coordinates, counters, ratios feeding a render. The exact value rarely is the deliverable.

In emissions accounting, the number is the deliverable. A reported figure of 1,240.37 tCO2e is the product. If an auditor recomputes it and gets 1,240.41, the 0.04 isn't noise — it's an unexplained discrepancy, and unexplained discrepancies are exactly what an audit exists to surface. You don't get to say "floating-point." You get to fix your data model.

Three properties of this domain turn a harmless rounding error into a real defect:

  • Massive summation. A Scope 3 inventory adds tens of thousands of line items. Error accumulates with count.
  • Wide dynamic range. You add a 4,000,000 kg figure to a 0.002 kg figure in the same total. This is precisely the case floating-point handles worst.
  • External reconciliation. The output is checked against an independent calculation. There's no hiding internal drift, because someone outside your system recomputes it.

The float problem, stated precisely

A 64-bit IEEE 754 float (double, JavaScript's only number type) stores 52 bits of mantissa — about 15–17 significant decimal digits. 0.1, 0.2, and 0.3 are not representable exactly in binary, the same way 1/3 isn't representable exactly in decimal. They're stored as the nearest available binary fraction, and the tiny errors survive arithmetic.

(0.1 + 0.2).toFixed(20)
// "0.30000000000000004441"

Enter fullscreen mode Exit fullscreen mode

For a single operation the error is ~10⁻¹⁷. The problem is what happens when you do the operation 50,000 times, and when the operands differ in magnitude by a factor of a billion.


Failure mode 1: the total that won't reconcile

Naive summation of a long list of factors:

function totalEmissions(lineItems) {
  let total = 0;
  for (const item of lineItems) {
    total += item.activity * item.factor;   // each term carries float error
  }
  return total;
}

Enter fullscreen mode Exit fullscreen mode

Each activity * item.factor lands on the nearest representable double, slightly off. Each += rounds again. Over tens of thousands of items the errors are mostly random and partly cancel — but "mostly" is not "exactly," and the residual is deterministic for a given input order. Run the same data through a spreadsheet that sums in a different order and you get a different last digit. Now you have two "correct" totals that disagree, and no way to say which is right.

Fix: control precision at the boundary, not in the loop

Two defensible strategies, depending on stack.

Decimal arithmetic for the money-and-mass path. Store and sum factors as arbitrary-precision decimals so there's no binary-representation error at all:

import Decimal from 'decimal.js';

function totalEmissions(lineItems) {
  return lineItems
    .reduce((acc, item) =>
      acc.plus(new Decimal(item.activity).times(item.factor)),
      new Decimal(0))
    .toNumber();   // convert once, at the very end, after rounding regime applied
}

Enter fullscreen mode Exit fullscreen mode

Decimal is slower. You don't need it everywhere — you need it on the path whose output is a reported figure.

Kahan summation when you must stay in floats. If the hot path can't afford Decimal, compensated summation recovers most of the lost low-order bits by tracking the rounding error and feeding it back in:

function kahanSum(values) {
  let sum = 0;
  let compensation = 0;        // running error term
  for (const v of values) {
    const y = v - compensation;
    const t = sum + y;
    compensation = (t - sum) - y;   // recovers what the addition just dropped
    sum = t;
  }
  return sum;
}

Enter fullscreen mode Exit fullscreen mode

The single addition sum + y loses the low bits of y when sum is large; the next line reconstructs exactly those bits and carries them into the following iteration. For a long sum of mixed-magnitude terms this is the difference between a stable total and one that drifts with input order.


Failure mode 2: the wide-magnitude swallow

This is the one that produces a wrong number, not just an unstable one.

let total = 4_000_000.0;   // a large facility's annual figure, kg
total += 0.002;            // a trace fugitive line, kg
total === 4_000_000.002;   // true here — but stack enough trace lines...

Enter fullscreen mode Exit fullscreen mode

When the accumulator is large and the addend is tiny, the addend's significant bits fall off the bottom of the mantissa and are silently dropped. One trace line is fine. Ten thousand of them, each individually swallowed, is a missing category total. The sum looks authoritative — it's a clean large number — which is exactly why nobody catches it by eye.

Fix: sum within magnitude bands, then combine

Add small things to small things before adding them to big things. Sort ascending and the smallest terms accumulate among themselves into a magnitude the large accumulator can actually absorb:

function bandedSum(values) {
  const ascending = [...values].sort((a, b) => a - b);
  return kahanSum(ascending);   // small-first ordering + compensation
}

Enter fullscreen mode Exit fullscreen mode

Sorting ascending before a compensated sum is a cheap, robust default for "many small, few large." It won't matter on uniform data — but reference-data sums are rarely uniform.


Failure mode 3: the ratio that amplifies

Intensity metrics divide one computed figure by another — emissions per unit revenue, per tonne of product, per kWh. Division doesn't create error, but it amplifies whatever error the operands already carry, and ratios of two nearly-equal slightly-wrong numbers are the worst case.

const intensityA = total2025 / output2025;
const intensityB = total2024 / output2024;
const yoyChange = (intensityA - intensityB) / intensityB;   // tiny - tiny, over tiny

Enter fullscreen mode Exit fullscreen mode

When intensityA and intensityB are close, their difference is dominated by the rounding error in each, and dividing that noisy difference by a small base inflates it into a visible percentage. Your year-on-year intensity change can read as ±0.3% pure artefact.

Fix: defer rounding, widen the working precision

Carry full precision through the entire chain and round once, at presentation. Never round an intermediate that feeds a later division. If the figures are reconciliation-critical, do the division in Decimal too — the cost is trivial relative to one division per report.


Failure mode 4: the unit-boundary shave

Every conversion is a multiply, and every multiply is a place to lose digits. The g → kg → t chain looks innocent:

const grams = 1234567;
const kg = grams / 1000;        // 1234.567
const tonnes = kg / 1000;       // 1.234567
// round-trip back up and compare:
tonnes * 1000 * 1000 === grams; // not guaranteed

Enter fullscreen mode Exit fullscreen mode

Each division lands on the nearest double; chaining them compounds the drift, and a value that round-trips through three units may not come back to where it started. The fix is the same architectural rule that governs the whole post: store in one canonical unit at full precision, convert only at the display boundary. Don't persist the converted value and re-derive from it — persist the canonical value and convert on read.


The rule underneath all four

Every one of these is the same decision made wrong: where does precision get fixed, and how many times. The failures all come from rounding early, rounding repeatedly, or rounding in the middle of a chain that isn't done yet.

The architecture that prevents all four:

  1. One canonical unit, full precision, in storage. No pre-rounded, pre-converted values persisted.
  2. A declared rounding regime, applied once, at the boundary. Half-up, half-even — pick one, document it, apply it where the number leaves the system, never before.
  3. Decimal on any path whose output is a reported figure. Floats are fine for charts and progress bars. They are not fine for the deliverable.
  4. Compensated, magnitude-aware summation wherever you must aggregate many terms in floating point.

This is the same shape as a rule we apply to every figure in the GreenCalculus data layer: a number is meaningless without its declared basis. There, the basis is the GWP version and the emission-factor source. Here, it's the unit and the rounding regime. In both cases the discipline is identical — the number is not just its digits; it's its digits plus the declared rules that produced them. Store the rules with the number, or you can't defend the number.

0.1 + 0.2 was never the bug. It was the warning that your numbers carry rules you haven't written down yet.


The GreenCalculus calculation layer applies these rules across 1,000+ emissions calculators, every one of which has to reconcile against its source data to the last reported digit. Methodology documentation at greencalculus.com.