集的sql代码

时间:2012-04-28 15:28:32

标签: sql sql-server

如何在sql中使用函数f(x,y)来计算这个系列:

f(x,y)=x-y^3/3!+x^5/5!-y^7/7!+....

我写了阶乘函数并使用while循环和计数直到参数< = 32和convert(varchar(50),@answer)

它可以在没有stackoverflow错误的情况下计算但是如何在此集合中使用此函数(或proc)?

如何在不使用阶乘函数的情况下模拟此集合?

例如

x^5/5!  

模拟
x^3/3!*x^2/5*4   .....

感谢您帮助我:)

2 个答案:

答案 0 :(得分:1)

如果只需要这个特定的无限级数,它会收敛到所有x的sin()和sinh()值的组合。 (检查我的数学,确保使用泰勒系列作为罪和罪。)

f(x,y) = (sin(x)-sinh(-x))/2 + (sin(y)+sinh(-y))/2

这表示没有循环所需的结果,但不幸的是,双曲线正弦函数sinh()在T-SQL中不可用。您可以通过为SQL Server创建CLR用户定义函数来使.NET math.sinh函数可用于SQL Server。 (您也可以使整个函数f(x,y)成为CLR函数。)

答案 1 :(得分:0)

我假设一系列因子(显示为3,5,7)随着奇数组的增加而增加。在此解决方案中,我使用公用表表达式,这意味着您必须使用SQL Server 2005或更高版本。

Declare @x float;
Declare @y float;

-- this is the first factor evaluated
-- e.g., in the example, 3 is the first factor
-- values less that one effectively set the min
-- to one.
Declare @FactorMin int;

-- this is the maximum number of iterations
-- i.e., 3, 5, 7, 
Declare @FactorMax int

Set @x = 20;
Set @y = 20;
Set @FactorMin = 3;
Set @FactorMax = 15;

With Numbers As
    (
    Select 1 As Value
    Union All
    Select Value + 1
    From Numbers
    Where Value < @FactorMax
    )
    , OddNumbers As
    (
    Select Value
        , Row_Number() Over( Order By Value ) As Position
    From Numbers
    Where Value % 2 = 1
        And Value Between @FactorMin And @FactorMax
    )
    , Factorials As
    (
    Select O.Value, O.Position
        , Exp(Sum(Log(N1.Value))) As Factorial
        , Case When O.Position % 2 = 1 Then -1 * @y Else @x End As XOrY
    From OddNumbers As O
        Cross Join Numbers As N1
    Where N1.Value <= O.Value
    Group By O.Value, O.Position
    )
Select Sum( Z.Value )
From    (
        Select @x As Value
        Union All   
        Select Power(XOrY, Value) / Factorial
        From Factorials 
        ) As Z  
Option (MaxRecursion 0);