简体   繁体   English

R中的实数和自然数

[英]Real and Natural numbers in R

I am trying to create a function which takes in an inputs and outputs the factorial of the number.我正在尝试创建一个函数,它接受输入并输出数字的阶乘。 If the input to the function is a real number, but not a natural number, round n to the nearest natural number and print a warning message alerting the user to this behavior.如果函数的输入是实数,但不是自然数,则将 n 舍入到最接近的自然数并打印警告消息,提醒用户注意此行为。

My questions is: How do I check if the input is real or natural number?我的问题是:如何检查输入是实数还是自然数?

This might help:这可能有帮助:

myFactorial <- function(x){
    if (any(x %% 1 != 0 | is.na(x))) message("Not all elements of the vector are natural numbers.")
    factorial(floor(x))
}

Here is a custom function这是一个自定义函数

f <- function(x) {
  if (x<=0 | x%%1!=0) warning("Input is not natural number!")
  factorial(max(1,as.integer(x)))
}

Example例子

> 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!

"How do I check if the input is real or natural number?" “如何检查输入是实数还是自然数?”

We can use as.integer我们可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM