stick-the-quick/util/ComplexMath.gd

43 lines
1.2 KiB
GDScript3
Raw Normal View History

class_name ComplexMath
func _init() -> void:
push_error("Not instantiable")
free()
static func mul(z: Vector2, w: Vector2) -> Vector2:
# (a + ib)(c + id) = ac + ibc + iad - bd
return Vector2(
z.x*w.x - z.y*w.y,
z.y*w.x + z.x*w.y
)
static func div(z: Vector2, w: Vector2) -> Vector2:
# (a + ib)(a - ib) = a^2 + aib - aib - (ib)^2 = a^2 + b^2
# ergo:
# (a + ib)/(c + id) = a/(c + id) + ib/(c + id)
# = a*(c - id)/(c^2 + d^2) + ib*(c - id)/(c^2 + d^2)
# = (ac - iad + ibc + bd)/(c^2 + d^2)
return Vector2(
z.x*w.x + z.y*w.y,
z.y*w.x - z.x*w.y
)/(w.x*w.x + w.y*w.y)
static func abs(z: Vector2) -> float:
return z.length()
static func arg(z: Vector2) -> float:
return atan2(z.y, z.x)
static func exp(z: Vector2) -> Vector2:
# e^(i*theta) = cos(theta) + i*sin(theta)
# ergo e^(a + ib) = (e^a)(e^(ib)) = (e^a)(cos(b) + i*sin(b))
return exp(z.x)*Vector2(cos(z.y), sin(z.y))
static func pow(z: Vector2, w: Vector2) -> Vector2:
# Credit to StackExchange user Shobhit for this formula
# <https://math.stackexchange.com/questions/476968\
# /complex-power-of-a-complex-number>.
var r: float = z.length()
var theta: float = ComplexMath.arg(z)
return ComplexMath.exp(ComplexMath.mul(Vector2(log(r), theta), w))