在一组复数中找出一个实数

Find a real number in a set of complex numbers

我正在寻找一种在 excel-vba 中的一组复数中找到实数的方法。更具体地说,我有一组三个结果,其中一个已知是真实的,两个已知是复杂的,但是,我不知道哪个结果是真实的。由于中间计算步骤中的舍入误差,经常会发生实数的虚部不完全抵消为 0(应该如此)这一事实,使问题变得更加复杂。

我目前考虑使用的方法包括以下步骤:

  1. 确定三个中每一个的Real分量的值 结果。
  2. 确定每个虚部的绝对值 三个结果。
  3. 确定这三个结果的最小值。
  4. 将每个绝对虚数分量与最小值进行比较。什么时候 这些匹配,取对应的实部作为最终 结果。

代码如下所示:

Z1 = Application.WorksheetFunction.ImReal ( Application.WorksheetFunction.ImSum (xi1, x1i2, x1i3) )
Z2 = Application.WorksheetFunction.ImReal ( Application.WorksheetFunction.ImSum (xi1, x2i2, x2i3) )
Z3 = Application.WorksheetFunction.ImReal ( Application.WorksheetFunction.ImSum (xi1, x3i2, x3i3) )
ZIm1 = Abs ( Application.WorksheetFunction.Imaginary ( Application.WorksheetFunction.ImSum (xi1, x1i2, x1i3) ) )
ZIm2 = Abs ( Application.WorksheetFunction.Imaginary ( Application.WorksheetFunction.ImSum (xi1, x2i2, x2i3) ) )
ZIm3 = Abs ( Application.WorksheetFunction.Imaginary ( Application.WorksheetFunction.ImSum (xi1, x3i2, x3i3) ) )
ZImMin = Min (ZIm1, ZIm2, ZIm3)
If Zim1 = ZImMin Then
    ZImID = Z1
    ElseIf Zim2 = ZImMin Then
    ZImID = Z2
    Else ZImID = Z3
EndIf

我认为这应该可行,但是,我还没有尝试 运行。谁能提出更好的方法来找到真正的解决方案?

此问题是根据 this method:

求三次方程解的一部分

谢谢!

我不仅会考虑虚部最接近零,还会考虑实部和虚部之间的关系。示例:
z1=2,35+0,25i
z2=14+1,3i

实际上 z2 更接近实数。对此的衡量标准是实部和复部之间的角度。 IMARGUMENT(z) returns 这个角度。 示例:

Public Function realIndex(rng As Range) As Long
' returns the row index into a column of complex values closest to a real number

    Dim values() As Variant
    Dim angle As Double, minangle As Double, i As Long, idx As Long

    values = rng  ' complex numbers in values(i,1)

    minangle = 100#
    For i = LBound(values, 1) To UBound(values, 1)
        angle = Application.WorksheetFunction.ImArgument(values(i, 1))
        If angle < minangle Then
            minangle = angle
            idx = i
        End If
    Next i
    realIndex = idx
End Function

编辑 回复评论:
采用 abs(sin(angle)) 可以减少围绕 -pi 的负角的模糊性。但是,由于 ImArgument 本质上是 arctan(Im(x)/Re(x)) 并且 sin(arctan(x)) 是等价的,我们可以使用:

Public Function MostReal(rng As Range) As Double
' returns from a column of complex values the one closest to a real number

    Dim values() As Variant
    Dim val As Double, minval As Double, absSize As Double, imSize As Double
    Dim i As Long, idx As Long

    values = rng  ' complex numbers in rows = values(i, 1)

    For i = 1 To UBound(values, 1)
        With Application.WorksheetFunction
            absSize = Abs(.Imaginary(values(i, 1)))
            imSize = .ImAbs(values(i, 1))
            val = IIf(imSize > 0#, absSize / imSize, 0#)
        End With
        If i = 1 Or val < minval Then
            minval = val
            idx = i
            If minval = 0# Then Exit For ' it doesn't get any better than this
        End If
    Next i
    realIndex = values(idx, 1)
End Function

判断标准是复数的虚部与绝对值之比——越接近零,越接近实数。第二个代码returns那个值(而不是值列的索引),它以更安全的方式选择初始最小值。