This is my code so far:
let x = tgamma(a b)
let y = tgamma(a)
let z = tgamma(b)
let norm = x / (y*z)
The type of 'x' is float. The problem in my code is that x reaches infinity too quickly. I am wondering whether there is a way to make the program store higher values for 'x'. Is that possible?
CodePudding user response:
You said
The type of 'x' is float.
Swift doesn't have a type “float”. It has a type Float
; in Swift, the capital letter is significant. I assume you meant that x
has type Float
.
The range of Float
is about -3.4×10³⁸ to 3.4×10³⁸. If you need more range, you can try using Double
, which has a range of about ±1.8×10³⁰⁸.
To use Double
, convert your inputs to Double
before calling tgamma
. Example:
let x = tgamma(Double(a) Double(b))
let y = tgamma(Double(a))
let z = tgamma(Double(b))
let norm = x / (y*z)
However, since tgamma
(aka Γ, the gamma function) grows quickly, you might want to use lgamma
instead. lgamma
returns the absolute value of the natural logarithm of Γ, so it returns finite answers for a much larger range of inputs. If your inputs are positive, this should work:
// log(x / (y * z)) = log x - (log y log z)
let lx: Double = lgamma(Double(a) Double(b))
let ly: Double = lgamma(Double(a))
let lz: Double = lgamma(Double(b))
let lnorm = lx - (ly lz)
let norm = exp(lnorm)
CodePudding user response:
You could use the logarithmic gamma function instead and replace multiplication and division with addition and subtraction of the calculated values
let x = lgamma(a b)
let y = lgamma(a)
let z = lgamma(b)
let norm = x.0 - (y.0 z.0)