如何实现阶乘函数代码? [英] How to implement factorial function into code?

查看:187
本文介绍了如何实现阶乘函数代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我使用泰勒级数来计算fortran90中的sin(0.75),直到某个点,所以我需要在do while循环中运行它(直到满足条件)。这意味着我需要使用factorial,这是我的代码:

 程序taylor 
隐式无
real :: x = 0.75
real :: y
integer :: i = 3
do while(abs(y - sin(0.75))> 10.00 **( - 7))
i = i + 2
y = x - ((x ** i)/ fact(i))
print *,y
end do
end program taylor

在哪里我写了fact(i)是我需要factorial的地方。不幸的是,Fortran没有内在的!功能。我将如何在此程序中实现此功能?



谢谢。

解决方案

<下面的简单功能回答你的问题。注意它是如何返回一个 real ,而不是一个整数。如果演出不是问题,那么对泰勒系列来说这是很好的。

 实际功能fact(n)
整数,意图(in):: n

整数:: i

if(n <0)错误停止'factorial对于负整数是单数'
fact = 1.0
do i = 2,n
fact = fact * i
enddo
end function fact

但真正的答案是Fortran 2008 does 具有阶乘的内在函数: Gamma函数。对于一个正整数 n ,它定义为 Gamma(n + 1)== fact(n)



(我可以想象 Gamma函数

a>是不熟悉的,它是阶乘函数的泛化: Gamma(x)是为所有复杂 x 定义的,除非是非正整数,定义中的偏移是出于历史原因,不必要的混淆你问我。)

So I am using the taylor series to calculate sin(0.75) in fortran 90 up until a certain point, so I need to run it in a do while loop (until my condition is met). This means I will need to use a factorial, here's my code:

program taylor
implicit none
real :: x = 0.75  
real :: y
integer :: i = 3
do while (abs(y - sin(0.75)) > 10.00**(-7)) 
 i = i + 2
 y = x - ((x**i)/fact(i))
 print *, y
end do
end program taylor

Where i've written fact(i) is where i'll need the factorial. Unfortunately, Fortran doesn't have an intrinsic ! function. How would I implement the function in this program?

Thanks.

解决方案

The following simple function answers your question. Note how it returns a real, not an integer. If performance is not an issue, then this is fine for the Taylor series.

real function fact(n)
  integer, intent(in) :: n

  integer :: i

  if (n < 0) error stop 'factorial is singular for negative integers'
  fact = 1.0
  do i = 2, n
    fact = fact * i
  enddo
end function fact

But the real answer is that Fortran 2008 does have an intrinsic function for the factorial: the Gamma function. For a positive integer n, it is defined such that Gamma(n+1) == fact(n).

(I can imagine the Gamma function is unfamiliar. It's a generalization of the factorial function: Gamma(x) is defined for all complex x, except non-positive integers. The offset in the definition is for historical reasons and unnecessarily confusing it you ask me.)

这篇关于如何实现阶乘函数代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆