2

私はこのコードを持っています:

static def parseString(String inputRow, Particle particle) {
        def map = inputRow.split()
        particle.mass = map[0].toDouble()
        particle.x = map[1].toDouble()
        particle.y = map[2].toDouble()
}

そして、このテストコード:

static final inputRow = "1 -5.2 3.8"
def particle1 = new Particle()

def "string should be parsed into particles"() {
    when:
    RepulsionForce.parseString(inputRow, particle1);

    then:
    particle1.mass == 1
    particle1.x == -5.2
    particle1.y == 3.8
}

上記のテストはそのままパスします。ただし、parseString コードを以下のコードに変更すると:

static def parseString(String inputRow, Particle particle) {
        def map = inputRow.split()
        particle.mass = map[0].toFloat()
        particle.x = map[1].toFloat()
        particle.y = map[2].toFloat()
}

同じテストが次のエラーで失敗します。

Condition not satisfied:

particle1.x == -5.2
|         | |
|         | false
|         -5.2
Particle@a548695
4

1 に答える 1

5

デフォルトで-5.2は、Groovy は BigDecimal であるため、BigDecimal を Float オブジェクトと比較しています。これらは次を通過します。

def a = -5.2
def b = "-5.2".toFloat()
assert a != b
assert a.getClass() == BigDecimal
assert b.getClass() == Float
assert a.toFloat() == b

Groovy は BigDecimal と Double の比較を受け入れます。

def g = -5.2
def h = "-5.2".toDouble()
assert g == h
assert g.getClass() == BigDecimal
assert h.getClass() == Double

精度を必要とするいくつかの計算を行う必要がある場合は、BigDecimal を使用する方が良いかもしれません。

def c = -5.2
def d = "-5.2".toBigDecimal()
assert c == d
assert c.getClass() == BigDecimal
assert d.getClass() == BigDecimal

それ以外の場合は、@Tim のコメントに従って、 を使用して-5.2f、比較が Float オブジェクトに対して行われるようにします。

def e = -5.2f
def f = "-5.2".toFloat()
assert e == f
assert e.getClass() == Float
assert f.getClass() == Float
于 2013-09-23T17:20:45.760 に答える