1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

complex, fraction: simplify and format source code

This commit is contained in:
hazohelet 2019-07-10 20:51:48 +09:00 committed by Alexander Medvednikov
parent 9907f07602
commit 00ea112b66
2 changed files with 48 additions and 50 deletions

View File

@ -26,10 +26,15 @@ pub fn (c Complex) str() string {
return out
}
// Complex Absolute value
// Complex Modulus value
// mod() and abs() return the same
pub fn (c Complex) abs() f64 {
return C.hypot(c.re, c.im)
}
pub fn (c Complex) mod() f64 {
return c.abs()
}
// Complex Angle
pub fn (c Complex) angle() f64 {
@ -93,40 +98,33 @@ pub fn (c1 Complex) divide(c2 Complex) Complex {
}
// Complex Conjugate
pub fn (c1 Complex) conjugate() Complex{
return Complex{c1.re,-c1.im}
pub fn (c Complex) conjugate() Complex{
return Complex{c.re, -c.im}
}
// Complex Additive Inverse
// Based on
// http://tutorial.math.lamar.edu/Extras/ComplexPrimer/Arithmetic.aspx
pub fn (c1 Complex) addinv() Complex {
return Complex{-c1.re,-c1.im}
pub fn (c Complex) addinv() Complex {
return Complex{-c.re, -c.im}
}
// Complex Multiplicative Inverse
// Based on
// http://tutorial.math.lamar.edu/Extras/ComplexPrimer/Arithmetic.aspx
pub fn (c1 Complex) mulinv() Complex {
pub fn (c Complex) mulinv() Complex {
return Complex {
c1.re / (pow(c1.re,2) + pow(c1.im,2)),
-c1.im / (pow(c1.re,2) + pow(c1.im,2))
c.re / (c.re * c.re + c.im * c.im),
-c.im / (c.re * c.re + c.im * c.im)
}
}
// Complex Mod or Absolute
// Based on
// http://tutorial.math.lamar.edu/Extras/ComplexPrimer/ConjugateModulus.aspx
pub fn (c1 Complex) mod() f64 {
return sqrt(pow(c1.re,2)+pow(c1.im,2))
}
// Complex Power
// Based on
// https://www.khanacademy.org/math/precalculus/imaginary-and-complex-numbers/multiplying-and-dividing-complex-numbers-in-polar-form/a/complex-number-polar-form-review
pub fn (c1 Complex) pow(n f64) Complex {
r := pow(c1.mod(),n)
angle := atan2(c1.im,c1.re)
pub fn (c Complex) pow(n f64) Complex {
r := pow(c.abs(), n)
angle := c.angle()
return Complex {
r * cos(n * angle),
r * sin(n * angle)
@ -134,29 +132,29 @@ pub fn (c1 Complex) pow(n f64) Complex {
}
// Complex nth root
pub fn (c1 Complex) root(n f64) Complex {
return c1.pow(1.0/n)
pub fn (c Complex) root(n f64) Complex {
return c.pow(1.0 / n)
}
// Complex Exponential
// Using Euler's Identity
// Based on
// https://www.math.wisc.edu/~angenent/Free-Lecture-Notes/freecomplexnumbers.pdf
pub fn (c1 Complex) exp() Complex {
a := exp(c1.re)
pub fn (c Complex) exp() Complex {
a := exp(c.re)
return Complex {
a * cos(c1.im),
a * sin(c1.im)
a * cos(c.im),
a * sin(c.im)
}
}
// Complex Natural Logarithm
// Based on
// http://www.chemistrylearning.com/logarithm-of-complex-number/
pub fn (c1 Complex) ln() Complex {
pub fn (c Complex) ln() Complex {
return Complex {
log(c1.mod()),
atan2(c1.im,c1.re)
log(c.abs()),
c.angle()
}
}