Numeric error propagation: Difference between revisions

Kotlin version
m (→‎{{header|C}}: Removed name as RC relies on page history for authorship.)
(Kotlin version)
Line 744:
}
}</lang>
{{out}}
Output:
<pre>111.80339887498948±2.938366893361004</pre>
 
=={{header|Kotlin}}==
{{trans|Java}}
<lang scala>import java.lang.Math.*
 
data class Approx(val value: Double = 0.0, val error: Double = 0.0) {
constructor(a: Approx) : this(a.value, a.error)
 
operator infix fun plus(a: Approx) = Approx(value + a.value, sqrt(error * error + a.error * a.error))
operator infix fun plus(d: Double) = Approx(value + d, error)
operator infix fun minus(a: Approx) = Approx(value - a.value, sqrt(error * error + a.error * a.error))
operator infix fun minus(d: Double) = Approx(value - d, error)
 
operator infix fun times(a: Approx): Approx {
val v = value * a.value
return Approx(v, sqrt(v * v * (error * error) / (value * value) + a.error * a.error / (a.value * a.value)))
}
 
operator infix fun times(d: Double) = Approx(value * d, abs(d * error))
 
operator infix fun div(a: Approx): Approx {
val v = value / a.value
return Approx(v, sqrt(v * v * (error * error) / (value * value) + a.error * a.error / (a.value * a.value)))
}
 
operator infix fun div(d: Double) = Approx(value / d, abs(d * error))
 
fun pow(d: Double): Approx {
val v = pow(value, d)
return Approx(v, abs(v * d * error / value))
}
 
override fun toString() = "$value ±$error"
}
 
fun main(args: Array<String>) {
val x1 = Approx(100.0, 1.1)
val x2 = Approx(50.0, 1.2)
val y1 = Approx(200.0, 2.2)
val y2 = Approx(100.0, 2.3)
println(((x1 - x2).pow(2.0) + (y1 - y2).pow(2.0)).pow(0.5)) // => 111.80339887498948 ±2.938366893361004
}</lang>
{{out}}
<pre>111.80339887498948 ±2.938366893361004</pre>
 
=={{header|Mathematica}}==
<lang mathematica>PlusMinus /: a_ ± σa_ + c_?NumericQ := N[(a + c) ± σa];
Anonymous user