Safe addition: Difference between revisions

Content added Content deleted
(Go solution)
Line 300: Line 300:
)
)


// type requested by task
type interval struct {
type interval struct {
lower, upper float64
lower, upper float64
}
}


// a constructor
func stepAway(x float64) interval {
return interval {
math.Nextafter(x, math.Inf(-1)),
math.Nextafter(x, math.Inf(1))}
}

// function requested by task
func safeAdd(a, b float64) interval {
func safeAdd(a, b float64) interval {
s := a + b
return stepAway(a + b)
return interval{
math.Nextafter(s, math.Inf(-1)),
math.Nextafter(s, math.Inf(1))}
}
}


// example
func main() {
func main() {
a, b := 1.2, .03
a, b := 1.2, .03
Line 319: Line 327:
1.2 0.03 {1.2299999999999998 1.2300000000000002}
1.2 0.03 {1.2299999999999998 1.2300000000000002}
</pre>
</pre>

=={{header|J}}==
=={{header|J}}==
J uses 64 bit IEEE floating points, providing 53 binary digits of accuracy.
J uses 64 bit IEEE floating points, providing 53 binary digits of accuracy.