2

我正在寻找一种在 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

我认为这应该可行,但是,我还没有尝试运行它。任何人都可以提出更好的方法来找到真正的解决方案吗?

此问题是根据此方法找到三次方程解的一部分:

谢谢!

4

1 回答 1

4

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

实际上 z2 更接近实数。对此的度量是实部和复部之间的角度。IMARGUMENT(z) 返回这个角度。例子:

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

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

于 2018-08-18T12:00:01.647 回答