3

I am writing some functions that will solve problems for me and it requires the use of ln (natural log) but I can't seem to find it in swift and I've searched all over the internet but I still can't find the answer. Any help would be appreciated.

let rate : Double = log(finalAmount / initalAmount) / time return rate

log should be ln.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Jaime Huerta
  • 31
  • 1
  • 2
  • 1
    The `log()` function in your question *is* the natural log function. – rmaddy Nov 23 '19 at 20:37
  • No, but `Foundation` has it. – Mojtaba Hosseini Nov 23 '19 at 20:41
  • @MojtabaHosseini: Actually, on macOS it is part of the system libraries, and imported via `import Darwin`. – Martin R Nov 23 '19 at 20:55
  • Possible duplicate of [Mathematical functions in Swift](https://stackoverflow.com/questions/24012511/mathematical-functions-in-swift). – Martin R Nov 23 '19 at 20:56
  • I don't get that @MartinR. Does Swift has it? Even if we run it on the server side or so? – Mojtaba Hosseini Nov 23 '19 at 20:57
  • @MojtabaHosseini: Swift can use the system libraries (such as the standard math library). `import Darwin` on Apple platforms or `import Glibc` on Linux. (Foundation also imports Darwin, so if you import Foundation then you already have it.) – Martin R Nov 23 '19 at 21:02
  • Such functions will be added to Swift. See [SE-0246](https://github.com/apple/swift-evolution/blob/master/proposals/0246-mathable.md) – ielyamani Nov 23 '19 at 21:58

1 Answers1

2

import Foundation and you'll find log() is implemented for all the real number types. As is log10() and other specialist log functions.

flanker
  • 3,840
  • 1
  • 12
  • 20
  • as correctly pointed out by @MartinR above, this is for iOS, and for MacOS its in the system libraries. For other platforms it will depend if they have ported Foundation or implemented an equivalent. – flanker Nov 23 '19 at 21:03
  • For iOS it is also in the system libraries (on all Apple platforms). – Martin R Nov 23 '19 at 21:04
  • it is? Unless I import Foundation I don't see it? – flanker Nov 23 '19 at 21:08
  • `import Darwin` should be sufficient, compare https://stackoverflow.com/a/24012755/1187415 or https://stackoverflow.com/a/34972828/1187415. – Martin R Nov 23 '19 at 21:10
  • Interesting read. Thanks. Do you know if Foundation re-implements the functions (i.e. are they in native Swift, as I believe Foundation now is?) or does it just import Darwen? – flanker Nov 23 '19 at 21:16