【问题标题】:Pythagorean Theorem in R programmingR编程中的勾股定理
【发布时间】:2019-07-28 11:53:51
【问题描述】:

我想为毕达哥拉斯定理写 R 代码。

勾股定理指出,斜边(直角的对边)的平方等于其他两条边的平方和。

(sideA)^2+(SideB)^2=斜边^2

现在我写的R代码如下:

pythag<-function(sidea,sideb){
if (sidea>=0&sideb>=0)
hypoteneuse=sqrt(sidea^2+sideb^2)
else if (sidea<0|sideb<0)
hypoteneuse<-"Values Need to be Positive"
else if (!is.vector(x))
hypoteneuse<-"I need numeric values to make this work"
print(hypoteneuse)
}
pythag(4,5)
pythag("A","B")
pythag(-4,-5)

如果是 pythag(4,5) 没问题,pythag(-4,-5) 也会给出评论“值需要为正”。

但在 pythag("A","B") 的情况下,我想评论“我需要数值来完成这项工作”,但不幸的是我的代码不适用于此。

【问题讨论】:

  • x 是什么?另外,如果x=c(sideA, sideB),那仍然是一个向量,而是一个字符串向量
  • is.vector() 测试某事物是否为向量,其中包括字符和因子向量。数字向量不是唯一的向量。
  • 另外——打印它们的输出而不是返回它们的函数在数学计算中不是很有用,因为它们不能以任何非常直接的方式作为更大的计算。 print() 主要用于调试功能,不返回值。
  • 主要问题是您首先计算斜边,假设所有输入都是有效的。应该是最后做的,检查必须是先验的。

标签: r pythagorean


【解决方案1】:

你可以这样试试:

get_hypotenuse_length <- function(height, base)
{
  sides <- c(height, base)
  if(any(sides < 0))
  {
    message("sides must be positive")
  } else if(!is.numeric(x = sides))
  {
    message("sides can not be non-numeric")
  } else
  {
    sqrt(x = sum(sides ^ 2))
  }
}

【讨论】:

    【解决方案2】:

    这是一个带注释的版本。它正在创建接受值ab 并计算c 的函数。它首先测试值是否为数字,如果它们不是数字,它将打印您的错误消息,否则它将忽略那些大括号内的内容并继续进行下一个测试。第二个测试是检查两者是否都大于零(看到三角形不能有长度为零或负长度的边)。如果它满足 both 都是 >0 的条件,那么它将计算 c,如果不满足,则会给出错误说明存在负值。

    # Feed it the values a and b (length of the two sides)
    pythag <- function(a,b){
    
      # Test that both are numeric - return error if either is not numeric
      if(is.numeric(a) == FALSE | is.numeric(b) == FALSE){
        return('I need numeric values to make this work')}
    
      # Test that both are positive - return length of hypoteneuese if true...
      if(a > 0 & b > 0){
        return(sqrt((a^2)+(b^2)))
      }else{
    
        # ... give an error either is not positive
        return('Values Need to be Positive')  
      }
    
    }
    

    这是一个更精简的版本:

    pythag <- function(a,b){
      if(is.numeric(a) == FALSE | is.numeric(b) == FALSE){return('I need numeric values to make this work')}
      if(a > 0 & b > 0){return(sqrt((a^2)+(b^2)))}
      else{return('Values Need to be Positive')}
      }
    

    这就是你的例子返回的结果:

    > pythag(4,5)
    [1] 6.403124
    > pythag("A","B")
    [1] "I need numeric values to make this work"
    > pythag(-4,-5)
    [1] "Values Need to be Positive"
    

    【讨论】:

      【解决方案3】:

      如果x = c("sideA", "sideB"),那么它仍然是一个向量,因此您的测试is.vector(x) 将返回true

      > is.vector(x)
      [1] TRUE
      

      但你想测试它是否是数字,所以如果它是数字:

      > is.numeric(x)
      [1] FALSE
      

      【讨论】:

      • 是的,要写什么来代替 is.vector(x),这样当我运行 pythag("A","B") 时,我们应该得到注释“我需要数值来完成这项工作”。而不是显示错误,它应该显示注释“它不适用于字符”
      猜你喜欢
      • 2016-03-24
      • 1970-01-01
      • 2015-07-23
      • 1970-01-01
      • 2013-02-13
      • 1970-01-01
      • 2021-09-20
      • 2019-10-08
      • 1970-01-01
      相关资源
      最近更新 更多