[英]Real and Natural numbers in R
我正在嘗試創建一個函數,它接受輸入並輸出數字的階乘。 如果函數的輸入是實數,但不是自然數,則將 n 舍入到最接近的自然數並打印警告消息,提醒用戶注意此行為。
我的問題是:如何檢查輸入是實數還是自然數?
這可能有幫助:
myFactorial <- function(x){
if (any(x %% 1 != 0 | is.na(x))) message("Not all elements of the vector are natural numbers.")
factorial(floor(x))
}
這是一個自定義函數
f <- function(x) {
if (x<=0 | x%%1!=0) warning("Input is not natural number!")
factorial(max(1,as.integer(x)))
}
例子
> f(3.5)
[1] 6
Warning message:
In f(3.5) : Input is not natural number!
> f(3)
[1] 6
> f(0.1)
[1] 1
Warning message:
In f(0.1) : Input is not natural number!
> f(-0.1)
[1] 1
Warning message:
In f(-0.1) : Input is not natural number!
“如何檢查輸入是實數還是自然數?”
我們可以使用as.integer
is.natural <- function(x) as.integer(x) == x & x > 0
is.natural(3)
[1] TRUE
is.natural(0)
[1] FALSE
is.natural(1.5)
[1] FALSE
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.