program tip

Swift의 수학 함수

radiobox 2020. 8. 28. 07:19
반응형

Swift의 수학 함수


어떻게 같은 수학 함수를 사용합니까 sqrt(), floor(), round(), sin(), 등?


할 때 :

_ = floor(2.0)
_ = sqrt(2.0)

나는 얻다:

오류 : 해결되지 않은 식별자 'floor'
사용 오류 : 해결되지 않은 식별자 'sqrt'사용

여기에 이미지 설명 입력


다른 언급했듯이 몇 가지 옵션이 있습니다. 수학 함수 만 원하는 경우. Darwin 만 가져올 수 있습니다.

import Darwin

수학 함수 및 기타 표준 클래스 및 함수를 원하는 경우. Foundation을 가져올 수 있습니다.

import Foundation

사용자 인터페이스에 대한 모든 것과 클래스를 원한다면 플레이 그라운드가 OS X 또는 iOS 용인지 여부에 따라 다릅니다.

OS X의 경우 Cocoa를 가져와야합니다.

import Cocoa

iOS의 경우 가져 오기 UIKit이 필요합니다.

import UIKit

File Inspector (⌥⌘1)를 열어 플레이 그라운드 플랫폼을 쉽게 찾을 수 있습니다.

플레이 그라운드 설정-플랫폼


정확히 말하면 다윈이면 충분합니다. 전체 Cocoa 프레임 워크를 가져올 필요가 없습니다.

import Darwin

물론 Cocoa, Foundation 또는 기타 상위 프레임 워크의 요소가 필요한 경우 대신 가져올 수 있습니다.


Linux, 즉 Ubuntu에서 swift [2.2]를 사용하는 사람들에게는 가져 오기가 다릅니다!

이를 수행하는 올바른 방법은 Glibc를 사용하는 것입니다. OS X 및 iOS에서는 기본 Unix 유사 API가 Darwin에 있지만 Linux에서는 Glibc에 있기 때문입니다. Importing Foundation은 그 자체로 구별을하지 않기 때문에 여기서 도움이되지 않습니다. 이렇게하려면 명시 적으로 직접 가져와야합니다.

#if os(macOS) || os(iOS)
import Darwin
#elseif os(Linux) || CYGWIN
import Glibc
#endif

당신은 재단 프레임 워크의 개발을 따를 수 있습니다 여기에 자세한 내용을 보려면


수정 : 2018 년 12 월 26 일

으로 지적 으로 쾨르 @ 빠른 3.0부터, 일부 수학 함수는 이제 유형 자체의 일부입니다. 예를 들어 Double 에는 이제 squareRoot 함수가 있습니다. 마찬가지로, ceil, floor, round, 모두 달성 될 수있다 Double.rounded(FloatingPointRoundingRule) -> Double.

게다가 우분투 18.04에 최신 안정 버전의 swift를 다운로드하여 설치했는데, Foundation프레임 워크 만 있으면 수학 함수에 액세스 할 수 있습니다. 이에 대한 문서를 찾으려고했지만 아무것도 나오지 않았습니다.

➜ swift          
Welcome to Swift version 4.2.1 (swift-4.2.1-RELEASE). Type :help for assistance.
  1> sqrt(9)
error: repl.swift:1:1: error: use of unresolved identifier 'sqrt'
sqrt(9)
^~~~


  1> import Foundation
  2> sqrt(9)
$R0: Double = 3
  3> floor(9.3)
$R1: Double = 9
  4> ceil(9.3) 
$R2: Double = 10

바로 인라인으로 사용할 수 있습니다.

var square = 9.4
var floored = floor(square)
var root = sqrt(floored)

println("Starting with \(square), we rounded down to \(floored), then took the square root to end up with \(root)")

수학 함수를 사용하려면 import Cocoa

You can see the other defined mathematical functions in the following way. Make a Cmd-Click on the function name sqrt and you enter the file with all other global math functions and constanst.

A small snippet of the file

...
func pow(_: CDouble, _: CDouble) -> CDouble

func sqrtf(_: CFloat) -> CFloat
func sqrt(_: CDouble) -> CDouble

func erff(_: CFloat) -> CFloat
...
var M_LN10: CDouble { get } /* loge(10)       */
var M_PI: CDouble { get } /* pi             */
var M_PI_2: CDouble { get } /* pi/2           */
var M_SQRT2: CDouble { get } /* sqrt(2)        */
...

For the Swift way of doing things, you can try and make use of the tools available in the Swift Standard Library. These should work on any platform that is able to run Swift.

Instead of floor(), round() and the rest of the rounding routines you can use rounded(_:):

let x = 6.5

// Equivalent to the C 'round' function:
print(x.rounded(.toNearestOrAwayFromZero))
// Prints "7.0"

// Equivalent to the C 'trunc' function:
print(x.rounded(.towardZero))
// Prints "6.0"

// Equivalent to the C 'ceil' function:
print(x.rounded(.up))
// Prints "7.0"

// Equivalent to the C 'floor' function:
print(x.rounded(.down))
// Prints "6.0"

These are currently available on Float and Double and it should be easy enough to convert to a CGFloat for example.

Instead of sqrt() there's the squareRoot() method on the FloatingPoint protocol. Again, both Float and Double conform to the FloatingPoint protocol:

let x = 4.0
let y = x.squareRoot()

삼각 함수의 경우 표준 라이브러리가 도움이되지 않으므로 Apple 플랫폼에서 Darwin을 가져 오거나 Linux에서 Glibc를 가져 오는 것이 가장 좋습니다. 손가락이 교차하면 앞으로 더 깔끔해질 것입니다.

#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif

let x = 1.571
print(sin(x))
// Prints "~1.0"

참고 URL : https://stackoverflow.com/questions/24012511/mathematical-functions-in-swift

반응형