gpt4 book ai didi

vba - 在一组复数中找到一个实数

转载 作者:行者123 更新时间:2023-12-03 01:31:52 24 4
gpt4 key购买 nike

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

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

  1. 确定三者中每一个的实数部分的值结果。
  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) 返回该角度。示例:

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

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

关于vba - 在一组复数中找到一个实数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51906614/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com