idea165-commonsgrid-communi.../idea165_commonsgrid_communi.../privacy.py

24 lines
632 B
Python

import math
import random
class PrivacyBudget:
def __init__(self, total_budget: float = 1.0):
self.total_budget = total_budget
self.used = 0.0
def spend(self, amount: float) -> bool:
if self.used + amount > self.total_budget + 1e-9:
return False
self.used += amount
return True
def remaining(self) -> float:
return max(self.total_budget - self.used, 0.0)
def laplace_noise(scale: float) -> float:
# Simple Laplace noise for DP; symmetric around 0
u = random.random() - 0.5
return -scale * math.copysign(1.0, u) * math.log(1.0 - 2.0 * abs(u))