個々の図形の領域を印刷して総面積(各領域の合計)を印刷すると思われるこのコードはありますが、どこかに問題があるようです私がインターフェイスとvariadic関数を使うときの追加。プログラムはGoLangで書かれており、以下はコードです。GoLangでの形状の面積の計算誤差
/* Program that interacts with shapes */
/* Calculating the area of basic shapes e.g Circle, Rectangle */
package main
import ("fmt"; "math")
/* Adding the interface support */
type Shape interface {
area() float64
}
/* Struct for Circle */
type Circle struct {
x, y, r float64
}
/* Struct for Rectangle */
type Rectangle struct {
x1, y1, x2, y2 float64
}
/* Calculation of distance */
func distance(x1, y1, x2, y2 float64) float64 {
a := x2 - x1
b := y2 - y1
return math.Sqrt(a*a + b*b)
}
/* Area of the rectangle */
func (r *Rectangle) area() float64 {
l := distance(r.x1, r.y1, r.x1, r.y2)
w := distance(r.x1, r.y1, r.x2, r.y1)
return l * w
}
/* Area of the circle */
func (c *Circle) area() float64 {
return math.Pi * c.r * c.r
}
/* Interface is really useful when finding the total area i.e. the sum of
all the areas of each of the shapes
*/
func totalArea(shapes ...Shape) float64 {
var area float64
for _, s := range shapes {
area += s.area()
}
return area
}
/* This is the main function */
func main() {
c := Circle{0, 0, 5}
r := Rectangle{0, 0, 10, 10}
fmt.Println("Area of the rectangle is: ", r.area())
fmt.Println("Area of the circle is: ", c.area())
fmt.Println("Sum of the areas: ", totalArea(&c, &r))
}
私は、私のMac OS Xエルキャピタン、コアi5の上でこのコードを実行した8ギガバイトのRAMと、以下のあなたが見ることができるような結果から、私の出力
Area of the rectangle is: 100
Area of the circle is: 78.53981633974483
Sum of the areas: 178.53981633974485
で、小さな問題があり、予想される領域の合計は178.53981633974483
でなければなりませんが、178.53981633974485
は0.00000000000002
と予想外の結果または逸脱しています。どうしてこのような理由で私を助けてください。
GoLangの数学ライブラリに問題があるかどうかは、2つの領域の通常の追加を行うだけで済んでいるとは思えません。それともGoLangがその領域をtotalArea()
に渡す前に再計算するのですか?それとも、それは私のコンピュータですか?事前にあなたの助けのための
感謝。
@tkausl、私はそれが問題を解決すると思う。うわー、本当に奇妙な。ハードウェア関連、それは理にかなっています。アーキテクチャは異なるため、データの格納方法は..ありがとう。 – d3r1ck