Skip to content

Accuracy loss in normalize/cross #1053

@Seelengrab

Description

@Seelengrab

Hi!

I've noticed a small loss in accuracy when computing mat * vec:

Without StaticArrays:

julia> lookMat = Float32[ -0.707107   0.707107  0.0       -0.0
        -0.485071  -0.485071  0.727607   0.485071
         0.514496   0.514496  0.685994  -3.42997
         0.0        0.0       0.0        1.0]
4×4 Matrix{Float32}:
 -0.707107   0.707107  0.0       -0.0
 -0.485071  -0.485071  0.727607   0.485071
  0.514496   0.514496  0.685994  -3.42997
  0.0        0.0       0.0        1.0

julia> lookMat * Float32[0.5, 0.5, 0, 1]
4-element Vector{Float32}:
  0.0
  0.0
 -2.9154742
  1.0

With StaticArrays loaded (no matter whether it's Float32 or Float64, the accuracy loss is the same - note the nonzero y component):

julia> Array(lookMat)
4×4 Matrix{Float64}:
 -0.707107   0.707107  0.0       -0.0
 -0.485071  -0.485071  0.727607   0.485071
  0.514496   0.514496  0.685994  -3.42997
  0.0        0.0       0.0        1.0

julia> Array(lookMat) * [0.5, 0.5, 0, 1]
4-element Vector{Float64}:
  0.0
  2.9802322387695312e-8
 -2.915476143360138
  1.0

The matrix is generated by this function:

function lookAt(eye, target, up)
    # up is local up of the camera
    zaxis = -normalize(target - eye)
    xaxis = normalize(cross(up, zaxis))
    yaxis = cross(zaxis, xaxis)

    res = @SMatrix Float32[
        xaxis[1]  xaxis[2]  xaxis[3]  -dot(eye, xaxis);
        yaxis[1]  yaxis[2]  yaxis[3]  -dot(eye, yaxis);
        zaxis[1]  zaxis[2]  zaxis[3]  -dot(eye, zaxis);
               0         0         0                 1
    ]

    return res
end

What this does, in essence, is orient a coordinate system with origin at (2,2,2) to point at target in the -z direction. So lookMat * target should be exactly a vector in -z direction.

Accuracy loss of the StaticArray version aside, is it expected that this also happens for the regular Array multiplication?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions