round_preserve_sum {guideR}R Documentation

Round values while preserve their rounded sum in R

Description

Sometimes, the sum of rounded numbers (e.g., using base::round()) is not the same as their rounded sum.

Usage

round_preserve_sum(x, digits = 0)

Arguments

x

Numerical vector to sum.

digits

Number of decimals for rounding.

Details

This solution applies the following algorithm

Value

A numerical vector of same length as x.

Source

https://biostatmatt.com/archives/2902

Examples

sum(c(0.333, 0.333, 0.334))
round(c(0.333, 0.333, 0.334), 2)
sum(round(c(0.333, 0.333, 0.334), 2))
round_preserve_sum(c(0.333, 0.333, 0.334), 2)
sum(round_preserve_sum(c(0.333, 0.333, 0.334), 2))

[Package guideR version 0.4.0 Index]