↑Wrench, J.W. (1968). Concerning two series for the gamma function. Mathematics of Computation, 22, 617–626. and Wrench, J.W. (1973). Erratum: Concerning two series for the gamma function. Mathematics of Computation, 27, 681–682.
localp={}localmath_liblocalto_numberfunctionp._init(_math_lib,_to_number)localwarp_funcs={"factorial","gamma","sec","csc","sech","csch","asec","acsc","asech","acsch","gd","cogd","arcgd","LambertW","norm","gcd","lcm","range","binomial",'minimum','maximum','average','min','max','avg','geoaverage','var','σ','selectlist','for','while','summation','product','if','iff','ifelse','ifelsef','diff','integral','∫','limit','hide','exprs','lastexpr','equalexpr',--調整條目中定義不顯示的函數'randomseed','time','nil','null','call','frameArg','object','string','symbols','passObject','typeof','length','array','assignMember','divisorsigma','findnext','findlast','divisor','primedivisor','eulerphi'}fori=1,#warp_funcsdoif_math_lib[warp_funcs[i]]==nilthen_math_lib[warp_funcs[i]]=p['_'..warp_funcs[i]]endendmath_lib=_math_libto_number=_to_numberreturn_math_libendfunctionp._complex_number()returnp._init(require("Module:Complex Number").cmath.init(),require("Module:Complex Number").cmath.init().toComplexNumber)endlocalnoop_func=function()endlocalfunctionassertArg(val,index,func)assert(val~=nil,string.format("bad argument #%d to '%s' (number expected, got %s)",index,func,type(val)))endfunctionp._binomial(cal_n,cal_k)localr_n=tonumber(tostring(cal_n))localr_k=tonumber(tostring(cal_k))ifr_nandr_kthenifr_n>0andr_k>=0thenlocalf_n,f_k;_,f_n=math.modf(r_n);_,f_k=math.modf(r_k)ifmath.abs(f_n)<1e-12andmath.abs(f_k)<1e-12thenlocalresult=1ifr_n==0thenreturnresultendwhiler_k>0doresult=result*r_n/r_kr_n=r_n-1r_k=r_k-1endreturnresultendendendlocaln=to_number(cal_n)localk=to_number(cal_k)assertArg(n,1,'binomial')assertArg(k,2,'binomial')returnp._factorial(n)*math_lib.inverse(p._factorial(k))*math_lib.inverse(p._factorial(n-k))endfunctionp._factorial(cal_z)returnp._gamma(to_number(cal_z)+1)endfunctionp._sec(cal_z)returnmath_lib.inverse(math_lib.cos(to_number(cal_z)))endfunctionp._csc(cal_z)returnmath_lib.inverse(math_lib.sin(to_number(cal_z)))endfunctionp._sech(cal_z)returnmath_lib.inverse(math_lib.cosh(to_number(cal_z)))endfunctionp._csch(cal_z)returnmath_lib.inverse(math_lib.sinh(to_number(cal_z)))endfunctionp._asec(cal_z)returnmath_lib.acos(math_lib.inverse(to_number(cal_z)))endfunctionp._acsc(cal_z)returnmath_lib.asin(math_lib.inverse(to_number(cal_z)))endfunctionp._asech(cal_z)returnmath_lib.acosh(math_lib.inverse(to_number(cal_z)))endfunctionp._acsch(cal_z)returnmath_lib.asinh(math_lib.inverse(to_number(cal_z)))endfunctionp._gd(cal_z)returnmath_lib.atan(math_lib.tanh(to_number(cal_z)*0.5))*2endfunctionp._arcgd(cal_z)returnmath_lib.atanh(math_lib.tan(to_number(cal_z)*0.5))*2endfunctionp._cogd(cal_z)localx=to_number(cal_z);return-math_lib.sgn(x)*math_lib.log(math_lib.abs(math_lib.tanh(x*0.5)))endfunctionp._range(val,vmin,vmax)assertArg(val,1,'range')localmin_inf,max_inf=tonumber("-inf"),tonumber("inf")localfunctionget_vector(_val)localval=to_number(_val)ifval==nilthenreturn{}endreturnmath_lib.tovector(val)endlocalv_val,v_min,v_max=math_lib.tovector(to_number(val)),get_vector(vmin),get_vector(vmax)fori=1,#v_valdolocalmin_v,max_v=math.min(v_min[i]ormin_inf,v_max[i]ormax_inf),math.max(v_min[i]ormin_inf,v_max[i]ormax_inf)ifv_val[i]<min_vorv_val[i]>max_vthenreturnto_number(math_lib.nan)endendreturnto_number(val)endfunctionp._calc_diff(_value,_left,_right,_expr)localvalue=to_number(_value)localleft=to_number(_left)localright=to_number(_right)localleft_val=_expr(value+left)localright_val=_expr(value+right)return(left_val-right_val)/(left-right)endfunctionp._diff_abramowitz_stegun(_x,_h,_f)localx=to_number(_x)localh=to_number(_h)local_1=to_number(1)local_2=to_number(2)local_8=to_number(8)local_12=to_number(12)--if tonumber(math_lib.abs(math_lib.nonRealPart(x))) > 1e-8 then-- --[[數值微分#複變的方法]] --(Martins, Sturdza et.al.)-- local _i = math_lib.i or _1-- return (math_lib.im(_f(x + _i * h))) / h--else--[[數值微分#高階方法]]--(Abramowitz & Stegun, Table 25.2)return(-_f(x+_2*h)+_8*_f(x+h)-_8*_f(x-h)+_f(x-_2*h))/(_12*h)--endendfunctionp._calc_from(_value,_left,_right,_expr)localvalue=to_number(_value)localleft=to_number(_left)localleft_val=_expr(value+left)returnleft_val-p._calc_diff(_value,_left,_right,_expr)*leftendfunctionp._get_sample_number(_value)localnum=math_lib.re(math_lib.abs(to_number(_value)))return(tonumber(num)~=nil)and((num<1e-8)and1ornum)or1endfunctionp._diff(_expr,_value)localfunc_type=type(noop_func)localvalue_str=tostring(_value)ifvalue_str=='nan'orvalue_str=='-nan'orvalue_str=='nil'thenerror("計算失敗:無效的數值 ")return_exprendifvalue_str=='inf'orvalue_str=='-inf'thenerror("計算失敗:不支援無窮微分 ")return_exprendlocalsmall_scale_pow=math_lib.floor(math_lib.log(p._get_sample_number(_value))/math_lib.log(to_number(10)))-5localsmall_scale=math_lib.pow(10,small_scale_pow)iftype(_expr)==func_typethenreturnp._diff_abramowitz_stegun(_value,small_scale,_expr)elsereturn0endendfunctionp._integral(_a,_b,func,step)locala=to_number(_a)localb=to_number(_b)localbegin_str=tostring(_a)localstop_str=tostring(_b)ifbegin_str=='nan'orbegin_str=='-nan'orbegin_str=='nil'orstop_str=='nan'orstop_str=='-nan'orstop_str=='nil'thenerror("計算失敗:無效的迴圈 ")returnfuncendifbegin_str=='inf'orbegin_str=='-inf'orstop_str=='inf'orstop_str=='-inf'thenerror("計算失敗:不支援無窮求積 ")returnfuncendlocaln=tonumber(step)or2000localf=(type(func)==type(noop_func))andfuncor(function()returnto_number(func)or0end)localh=(b-a)/nlocalx0,xn=a,blocal_2,_7,_12,_14,_32,_45=to_number(2),to_number(7),to_number(12),to_number(14),to_number(32),to_number(45)locali0,i1,i2=1,2,4localsumfxi0,sumfxi1,sumfxi2=to_number(0),to_number(0),to_number(0)fori=1,ndo-- Boole's ruleifi0>n-1andi1>n-2andi2>n-4thenbreakendlocalxi0,xi1,xi2=a+i0*h,a+i1*h,a+i2*hifi0<=n-1thensumfxi0=sumfxi0+f(xi0)endifi1<=n-2thensumfxi1=sumfxi1+f(xi1)endifi1<=n-4thensumfxi2=sumfxi2+f(xi2)endi0=i0+2i1=i1+4i2=i2+4endreturn(_2*h/_45)*(_7*(f(x0)+f(xn))+_32*sumfxi0+_12*sumfxi1+_14*sumfxi2)endp['_∫']=p._integralfunctionp._limit(_value,_way,_expr)localway=to_number(_way)localfunc_type=type(noop_func)localvalue_str=tostring(_value)ifvalue_str=='nan'orvalue_str=='-nan'orvalue_str=='nil'thenerror("計算失敗:無效的數值 ")return_exprendifvalue_str=='inf'orvalue_str=='-inf'thenerror("計算失敗:不支援無窮極限 ")return_exprendlocalsmall_scale_pow=tonumber(math_lib.re(math_lib.floor(math_lib.log(p._get_sample_number(_value))/math_lib.log(to_number(10))))-6)localsmall_scale=math.pow(10,small_scale_pow)localsmall_scale_a=small_scale/10localsmall_scale_c=small_scale*10iftype(_expr)==func_typethenifmath_lib.re(math_lib.abs(way))<1e-10thenlocalleft=p._calc_from(_value,-small_scale,-small_scale_a,_expr)localright=p._calc_from(_value,small_scale_a,small_scale,_expr)ifmath_lib.re(math_lib.abs(left-right))<small_scale_cthenreturn(left+right)/2elsereturnmath_lib.nanendelsereturn(math_lib.re(way)>0)andp._calc_from(_value,small_scale_a,small_scale,_expr)orp._calc_from(_value,-small_scale,-small_scale_a,_expr)endelsereturn_exprendendp._nil="nil"p._null="nil"---------------------- 流程控制擴充 ----------------------functionp._if(_expr,_true_expr,_false_expr)returnp._ifelse_func(false,_expr,_true_expr,_false_expr)endfunctionp._iff(_expr,_true_expr,_false_expr)returnp._ifelse_func(true,_expr,_true_expr,_false_expr)endfunctionp._ifelse(...)returnp._ifelse_func(false,...)endfunctionp._ifelsef(...)returnp._ifelse_func(true,...)endfunctionp._ifelse_func(is_func,...)localfunc=noop_funclocalexprlist={...}locallast_else=#exprlist%2==1localmax_num=(last_elseand(#exprlist-1)or#exprlist)/2fori=1,max_numdolocal_expr=exprlist[i*2-1]localexpr=(type(_expr)==type(func))and_expr()or_exprlocalexpr_true=exprlist[i*2]local_chk_flag=math_lib.abs(to_number(expr))>1e-14;if_chk_flagthenreturn(type(expr_true)==type(func)andis_func)andexpr_true()orexpr_trueendendiflast_elsethenlocalexpr_false=exprlist[#exprlist]return(type(expr_false)==type(func)andis_func)andexpr_false()orexpr_falseendlocal_expr=exprlist[1]return(type(_expr)==type(func))and_expr()or_exprendlocalfunctioncheck_while(_ifexpr)localresult=(type(_ifexpr)==type(noop_func))and_ifexpr()or_ifexprifresult==truethenreturntrueendifnotresultthenreturnfalseendreturnmath_lib.abs(to_number(result))>1e-14endfunctionp._while(_ifexpr,_expr)localresultwhilecheck_while(_ifexpr)doresult=(type(_expr)==type(noop_func))and_expr()or_expriftype(result)==type({})andresult['return']thenbreakendendreturnresultendfunctionp._for(_start,_end,_step,_expr)local_begin=to_number(_start);local_stop=to_number(_end);local_do_step=to_number(_step);localcheck_loop=(_stop-_begin)/_do_steplocalbegin_str=tostring(_begin)localstop_str=tostring(_stop)ifmath_lib.re(math_lib.abs(_do_step))<=1e-14ormath_lib.re(check_loop)<0orbegin_str=='nan'orbegin_str=='-nan'orbegin_str=='nil'orbegin_str=='inf'orbegin_str=='-inf'orstop_str=='nan'orstop_str=='-nan'orstop_str=='nil'orstop_str=='inf'orstop_str=='-inf'thenerror("計算失敗:無效的迴圈 ")return_exprendiftype(_expr)==type(noop_func)thenlocalit=_beginlocalinit=to_number(0)whilemath_lib.re(it)<=math_lib.re(_stop)doinit=_expr(to_number(it),to_number(init))iftype(init)==type({})andinit['return']thenbreakendit=it+_do_stependreturninitelsereturn_exprendendfunctionp._summation(_start,_end,_expr)local_begin=to_number(_start);local_stop=to_number(_end);local_do_step=to_number(1);localcheck_loop=(_stop-_begin)/_do_steplocalbegin_str=tostring(_begin)localstop_str=tostring(_stop)ifmath_lib.re(math_lib.abs(_do_step))<=1e-14ormath_lib.re(check_loop)<0orbegin_str=='nan'orbegin_str=='-nan'orbegin_str=='nil'orstop_str=='nan'orstop_str=='-nan'orstop_str=='nil'thenerror("計算失敗:無效的迴圈 ")return_exprendifbegin_str=='inf'orbegin_str=='-inf'orstop_str=='inf'orstop_str=='-inf'thenerror("計算失敗:不支援無窮求和 ")return_exprendlocalfunc_type=type(noop_func)localit=_beginlocalinit=to_number(0)--空和whilemath_lib.re(it)<=math_lib.re(_stop)doinit=init+((type(_expr)==func_type)and_expr(to_number(it))orto_number(_expr))--累加it=it+_do_stependreturninitendfunctionp._product(_start,_end,_expr)local_begin=to_number(_start);local_stop=to_number(_end);local_do_step=to_number(1);localcheck_loop=(_stop-_begin)/_do_steplocalbegin_str=tostring(_begin)localstop_str=tostring(_stop)ifmath_lib.re(math_lib.abs(_do_step))<=1e-14ormath_lib.re(check_loop)<0orbegin_str=='nan'orbegin_str=='-nan'orbegin_str=='nil'orstop_str=='nan'orstop_str=='-nan'orstop_str=='nil'thenerror("計算失敗:無效的迴圈 ")return_exprendifbegin_str=='inf'orbegin_str=='-inf'orstop_str=='inf'orstop_str=='-inf'thenerror("計算失敗:不支援無窮求積 ")return_exprendlocalfunc_type=type(noop_func)localit=_beginlocalinit=to_number(1)--空積whilemath_lib.re(it)<=math_lib.re(_stop)doinit=init*((type(_expr)==func_type)and_expr(to_number(it))orto_number(_expr))--累乘it=it+_do_stependreturninitend---------------------- 工具函數擴充 ----------------------functionp._randomseed(_seed)localseed=tonumber(tostring(_seed))or(os.time()*os.clock())math.randomseed(math.floor(seed))returnto_number(seed)endfunctionp._time()returnto_number(os.time())endfunctionp._call(func,...)iftype(func)==type(noop_func)thenreturnfunc(...)endreturnfuncendfunctionp._hide(...)localinput_args={...}returnto_number(input_args[#input_args])endp._exprs=p._hidep._lastexpr=p._hidep._equalexpr=p._hide---------------------- 統計函數 ----------------------functionp._selectlist(x,...)localinput_args={...}localy=input_args[1]localz=input_args[2]localid_x=tonumber(tostring(x))or0iftype(y)==type("string")thenreturnmw.ustring.sub(y,id_x,id_x)endiftype(y)==type({})and#y>=id_xandid_x>0thenifid_x<=0thenid_x=id_x+#y+1endreturny[id_x]ortonumber('nan')elseiftype(z)==type({})and#z>=id_xthenlocalid_y=tonumber(tostring(y))or0ifid_x<=0thenid_x=id_x+#z+1endiftype(z[id_x])==type({})and#(z[id_x])>=id_yandid_y>0thenifid_y<=0thenid_y=id_y+#(z[id_x])+1endreturn(z[id_x][id_y])ortonumber('nan')endendid_x=tonumber(tostring(x))or0ifid_x<=0thenid_x=id_x+#input_args+1endreturninput_args[id_x]ortonumber('nan')endfunctionp._minimum(...)returnp.minmax('min',...)endfunctionp._maximum(...)returnp.minmax('max',...)endfunctionp._average(...)returnp.minmax('avg',...)endfunctionp._geoaverage(...)returnp.minmax('gavg',...)endfunctionp._var(...)returnp.minmax('var',...)endp._min=p._minimump._max=p._maximump._avg=p._averagep['_σ']=function(...)returnp.minmax('σ',...)endlocalfunctionflatten(inarray,outarray)outarray=outarrayor{}iftype(inarray)~=type({})thenoutarray[#outarray+1]=inarrayelseifinarray.numberTypethenoutarray[#outarray+1]=inarrayelseiftype(inarray.args)==type({})thenlocalmidarray=inarray.argsfork,vinpairs(midarray)dolocali=tonumber(k)ifithenoutarray=flatten(midarray[i],outarray)endendiftype(inarray.getParent)==type(noop_func)thenmidarray=(inarray:getParent()or{}).argsor{}fork,vinpairs(midarray)dolocali=tonumber(k)ifithenoutarray=flatten(midarray[i],outarray)endendendelseif#inarray>0thenfori=1,#inarraydooutarray=flatten(inarray[i],outarray)endendreturnoutarrayendfunctionp.minmax(calc_mode,...)localmode=calc_modelocaltonumber_lib=to_numberortonumberlocallib_math=math_libormathlocalargs,tester=flatten({...}),{tonumber("nan")}iftype(calc_mode)==type({})thenmode=(calc_mode.argsorcalc_mode).modeormode;args=flatten({args,calc_mode})endlocalsum,prod,count,sumsq,sig=tonumber_lib(0),tonumber_lib(1),0,tonumber_lib(0),(mode=='var'ormode=='σ')localmode_map={}localnon_nanfori=1,#argsdolocalgot_number,calc_number=tonumber(tostring(args[i]))ortonumber("nan"),tonumber_lib(args[i])ifcalc_numberthensum,prod,count=calc_number+sum,calc_number*prod,count+1endifsig==truethenlocalx_2=calc_number*calc_numberiflib_math.dotthenx_2=lib_math.dot(calc_number,lib_math.conjugate(calc_number))endsumsq=sumsq+x_2endmode_map[args[i]]=(mode_map[args[i]]or0)+1iftostring(got_number):lower()~="nan"andtype(non_nan)==type(nil)thentester[1],non_nan=got_number,got_numberelsetester[#tester+1]=got_numberendendlocalmodes={min=math.min,max=math.max,sum=function()returnsumend,prod=function()returnprodend,count=function()returncountend,avg=function()returnsum*tonumber_lib(1/count)end,gavg=function()returnlib_math.pow(prod,tonumber_lib(1/count))end,var=function()returnsumsq*tonumber_lib(1/count)-sum*sum*tonumber_lib(1/(count*count))end,['σ']=function()returnlib_math.sqrt(sumsq*tonumber_lib(1/count)-sum*sum*tonumber_lib(1/(count*count)))end,mode=function()localmax_count,mode_data=0,''formkey,mvalinpairs(mode_map)doifmval>max_countthenmax_count=mvalmode_data=mkeyendendreturnmode_dataend,gcd=function(...)ifnotto_numberornotmath_libthenp._complex_number()endreturnp._gcd(...)end,lcm=function(...)ifnotto_numberornotmath_libthenp._complex_number()endreturnp._lcm(...)end,}iftostring(tester[1]):lower()=="nan"andmode:sub(1,1)=='m'thenlocalerror_msg=''fori=1,#argsdoiferror_msg~=''thenerror_msg=error_msg..'、 'enderror_msg=error_msg..tostring(args[i])enderror("給定的數字 "..error_msg.." 無法比較大小")endiftype(modes[mode])~=type(tonumber)thenerror("未知的統計方式 '"..mode.."' ")endreturnmodes[mode](unpack(tester))endlocalfunctionfold(func,...)-- Use a function on all supplied arguments, and return the result. The function must accept two numbers as parameters,-- and must return a number as an output. This number is then supplied as input to the next function call.localvals={...}localcount=#vals-- The number of valid argumentsifcount==0thenreturn-- Exit if we have no valid args, otherwise removing the first arg would cause an error.nil,0endlocalret=table.remove(vals,1)for_,valinipairs(vals)doret=func(ret,val)endreturnret,countend--[[Fold arguments by selectively choosing values (func should return when to choose the current "dominant" value).]]localfunctionbinary_fold(func,...)localvalue=fold((function(a,b)iffunc(a,b)thenreturnaelsereturnbendend),...)returnvalueend---------------------- 伽瑪函數 ----------------------localReciprocal_gamma_coeff={1,0.577215664901532860607,-0.655878071520253881077,-0.0420026350340952355290,0.166538611382291489502,-0.0421977345555443367482,-0.00962197152787697356211,0.00721894324666309954240,-0.00116516759185906511211,-0.000215241674114950972816,0.000128050282388116186153,-0.0000201348547807882386557,-1.25049348214267065735e-6,1.13302723198169588237e-6,-2.05633841697760710345e-7,6.11609510448141581786e-9,5.00200764446922293006e-9,-1.18127457048702014459e-9,1.04342671169110051049e-10,7.78226343990507125405e-12,-3.69680561864220570819e-12,5.10037028745447597902e-13,-2.05832605356650678322e-14,-5.34812253942301798237e-15,1.22677862823826079016e-15,-1.18125930169745876951e-16,1.18669225475160033258e-18,1.41238065531803178156e-18,-2.29874568443537020659e-19,1.71440632192733743338e-20}--https://oeis.org/A001163 、 https://oeis.org/A001164localstirling_series_coeff={1,0.0833333333333333333333333,0.00347222222222222222222222,-0.00268132716049382716049383,-0.000229472093621399176954733,0.000784039221720066627474035,0.0000697281375836585777429399,-0.000592166437353693882864836,-0.0000517179090826059219337058,0.000839498720672087279993358,0.0000720489541602001055908572,-0.00191443849856547752650090,-0.000162516262783915816898635,0.00640336283380806979482364,0.000540164767892604515180468,-0.0295278809456991205054407,-0.00248174360026499773091566,0.179540117061234856107699,0.0150561130400264244123842,-1.39180109326533748139915,-0.116546276599463200850734}functionp._gamma_high_imag(cal_z)localz=to_number(cal_z)ifz~=nilandmath_lib.abs(math_lib.nonRealPart(z))>2thenlocalinv_z=math_lib.inverse(z)returnmath_lib.sqrt((math_lib.pi*2)*inv_z)*math_lib.pow(z*math_lib.exp(-1)*math_lib.sqrt((z*math_lib.sinh(inv_z))+math_lib.inverse(to_number(810)*z*z*z*z*z*z)),z)endreturnnilendfunctionp._gamma_morethen_lua_int(cal_z)localz=to_number(cal_z)-to_number(1)locallua_int_term=18.1169--FindRoot[ Factorial[ x ] == 2 ^ 53, {x, 20} ]ifmath_lib.abs(z)>(lua_int_term-1)or(math_lib.re(z)<0andmath_lib.abs(math_lib.nonRealPart(z))>1)thenlocalsum=1fori=1,#stirling_series_coeff-1dolocala,n=to_number(z),tonumber(i)localy,k,f=to_number(1),n,to_number(a)whilek~=0doifk%2==1theny=y*fendk=math.floor(k/2);f=f*fendsum=sum+stirling_series_coeff[i+1]*math_lib.inverse(y)endreturnmath_lib.sqrt((2*math.pi)*z)*math_lib.pow(z*math.exp(-1),z)*sumendreturnnilendfunctionp._gamma_abs_less1(cal_z)localz=to_number(cal_z)if(math.abs(math_lib.re(z))<=1.001)thenifmath_lib.abs(math_lib.nonRealPart(z))<1e-14and((math.abs(math_lib.re(z)-1)<1e-14)or(math.abs(math_lib.re(z)-2)<1e-14))thenreturnto_number(1)endreturnmath_lib.inverse(p._recigamma_abs_less1(z))endreturnnilendfunctionp._recigamma_abs_less1(z)localresult=to_number(0)fori=1,#Reciprocal_gamma_coeffdoresult=result+Reciprocal_gamma_coeff[i]*math_lib.pow(z,i)endreturnresultendfunctionp._gamma(cal_z)localz=to_number(cal_z)ifmath_lib.abs(math_lib.nonRealPart(z))<1e-14and((math_lib.re(z)<0ormath.abs(math_lib.re(z))<1e-14)andmath.abs(math.floor(math_lib.re(z))-math_lib.re(z))<1e-14)thenreturntonumber("nan")endlocalpre_result=p._gamma_morethen_lua_int(z)orp._gamma_high_imag(z)orp._gamma_abs_less1(z)ifpre_resultthenreturnpre_resultendlocalreal_check=math_lib.re(z)localloop_count=math.floor(real_check)localstart_number,zero_flag=z-loop_count,falseifmath_lib.abs(start_number)<=1e-14thenstart_number=to_number(1);zero_flag=trueendlocalresult=math_lib.inverse(p._recigamma_abs_less1(start_number))ifmath_lib.abs(math_lib.nonRealPart(z))<1e-14and((math_lib.re(z)>1e-14)andmath.abs(math.floor(math_lib.re(z))-math_lib.re(z))<1e-14)thenresult=to_number(1)endlocalj=to_number(start_number)fori=1,math.abs(loop_count)doifloop_count>0thenresult=result*jelseresult=result*math_lib.inverse(j-1)endifzero_flag==trueandloop_count>0thenzero_flag=falseelseifloop_count>0thenj=j+1elsej=j-1endendendifmath_lib.abs(math_lib.nonRealPart(z))<1e-14and((math_lib.re(z)>1e-14)andmath.abs(math.floor(math_lib.re(z))-math_lib.re(z))<1e-14)thenreturnmath_lib.floor(result)endreturnresultend---------------------- 最大公因數與最小公倍數 ----------------------localfunctionfindGcd(a,b)localr,oldr=to_number(b),to_number(a)whilemath_lib.abs(r)>1e-6dolocalmod_val=oldr%roldr,r=to_number(r),mod_valendifmath_lib.abs(math_lib.nonRealPart(oldr))<1e-14and(math_lib.re(oldr)<0)thenoldr=-oldrendreturnoldrendfunctionp._gcd(...)localresult,count=fold(findGcd,...)returnresultendfunctionp._lcm(...)localfunctionfindLcm(_a,_b)locala,b=to_number(_b),to_number(_a)returnmath_lib.abs(a*b)/findGcd(a,b)endlocalresult,count=fold(findLcm,...)returnresultend---------------------- 字串與物件擴充 (提供Module:Complex Number/Calculate使用) ----------------------functionp._symbols(name)return({comma=',',space=' ',colon=':',dot='.',squot="'",dquot='"',semicolon=';',underline='_',lcbracket='{',rcbracket='}',lsbracket='[',rsbracket=']',lpbracket='(',rpbracket=')',plus='+',minus='-',mul='*',div='/',['pow']='^',equal='=',lt='<',gt='>',money='$',percent='%',['and']='&',exclamation='!',at='@',hashtag='#',to='~',slash='\\'})[name]endfunctionp._frameArg(str)localframe=mw.getCurrentFrame()localworking_frame=frame:getParent()orframelocalargname=tonumber(tostring(str))ortostring(str)returnworking_frame.args[argname]orframe.args[argname]endfunctionp._string(str,...)localresult=tostring(str)localstr_list={...}fori=1,#str_listdoresult=result..''..tostring(str_list[i])endreturnresultendfunctionp._passObject(obj)returnobjendfunctionp._assignMember(obj,member,value)localinput_obj=objiftype(obj)==type("string")theninput_obj=_G[obj]endiftype(obj)==type(0)ortype(input_obj)==type(0)thenerror("無法傳值給數字",2)endiftype(obj)==type(noop_func)ortype(input_obj)==type(noop_func)thenerror("無法傳值給函數",2)endifinput_obj==nilthenerror("無法傳值給空值",2)endinput_obj[member]=valuereturnvalueendfunctionp._object(obj,...)localinput_obj=objiftype(obj)==type("string")theninput_obj=_G[obj]endiftype(obj)==type(0)thenreturnobjendiftype(obj)==type(noop_func)thenreturnobjendifinput_obj==nilthenreturnnilendlocalmembers={...}if#members>0thenlocalit_obj=input_objfori=1,#membersdoiftype(it_obj)~=type({})thenreturnnilendit_obj=(it_objor{})[members[i]]ifit_obj==nilthenreturnnilendendreturnit_objendreturninput_objendfunctionp._typeof(obj)iftype(obj)==type({})thenifobj.numberTypethenreturntype(0)endlocalis_array=trueforindex,datainpairs(obj)doifnottonumber(index)andindex~='metatable'thenis_array=falsebreakendendifis_arraythenreturn'array'endendreturntype(obj)endfunctionp._array(...)return{...}endfunctionp._length(obj)iftype(obj)==type({})thenifobj.numberTypethenreturn1endlocalmax_index=0forkey,datainpairs(obj)dolocalindex=tonumber(key)if(indexor0)>max_indexthenmax_index=indexendendreturnmax_indexelseiftype(obj)==type("string")thenreturnmw.ustring.len(obj)elsereturn1endend---------------------- 數論相關 ----------------------functionp._findnext(func,x)localit=to_number(x)+1iftype(func)~=type(noop_func)thenifmath_lib.abs(to_number(func))<1e-14thenreturnto_number("inf")elsereturnitendendlocalchecker=func(it)whilemath_lib.abs(to_number(checker))<1e-14doit=it+1checker=func(it)endreturnitendfunctionp._findlast(func,x)localit=to_number(x)-1iftype(func)~=type(noop_func)thenifmath_lib.abs(to_number(func))<1e-14thenreturnto_number("-inf")elsereturnitendendlocalchecker=func(it)whilemath_lib.abs(to_number(checker))<1e-14doit=it-1checker=func(it)endreturnitendlocalfunctionkey_sort(t)iftype(t)~=type({"table"})thenreturn{t}endlocalkey_list={}fork,vinpairs(t)dokey_list[#key_list+1]=kendtable.sort(key_list)returnkey_listendlocalfunctionget_divisor(n,combination)localis_complex=math_lib.abs(math_lib.nonRealPart(n))>1e-14localfactors={}ifmath_lib.abs(math_lib.floor(n)-n)<1e-14thenlocallib_factor=require('Module:Factorization')factors=(lib_factor[is_complexand"_gaussianFactorization"or"_factorization"])(is_complexandnortonumber(tostring(n)))elsereturncombinationand{{n}}or{}endifnotcombinationthenreturnfactorsendlocalgened=require('Module:Combination').getCombinationGenerator()gened:init(factors,0)returngened:findSubset()endfunctionp._primedivisor(_n,_x)localn=to_number(_n)ifmath_lib.abs(n)<1e-14thenreturn0endlocalis_complex=math_lib.abs(math_lib.nonRealPart(n))>1e-14ifnotis_complexthenn=math_lib.abs(n)endlocalprimedivisors=key_sort(get_divisor(n,false))returnprimedivisors[math_lib.abs(to_number(_xor#primedivisors))]or0endfunctionp._eulerphi(_n,_x)localn=to_number(_n)ifmath_lib.abs(n)<1e-14thenreturn0endlocalis_complex=math_lib.abs(math_lib.nonRealPart(n))>1e-14ifnotis_complexandmath_lib.re(n)<1e-14thenreturn0endlocalprimedivisors=get_divisor(n,false)localresult=1forp,kinpairs(primedivisors)dolocalp_r=to_number(p)localk_r=to_number(k)result=result*math_lib.pow(p_r,k_r-1)*(p_r-1)endreturnresultendfunctionp._divisor(_n,_x)localn=to_number(_n)localfunction_index(total)return(total<=2)andtotalor(total-1)endifmath_lib.abs(n)<1e-14thenreturn0endlocalis_complex=math_lib.abs(math_lib.nonRealPart(n))>1e-14ifnotis_complexthenn=math_lib.abs(n)endlocalcombination=get_divisor(n,true)localdivisors={}fori=1,#combinationdolocaldivisor=to_number(1)forj=1,#(combination[i])dodivisor=divisor*to_number(combination[i][j])enddivisors[#divisors+1]=divisorendtable.sort(divisors,function(a,b)returnmath_lib.abs(a)<math_lib.abs(b)end)returndivisors[math_lib.abs(to_number(_xor_index(#divisors)))]or0endfunctionp._divisorsigma(_x,_n)localx=to_number(1),nif_n==nilthenn=to_number(_x)elsex=to_number(_x)n=to_number(_n)endifmath_lib.abs(n)<1e-14thenreturn0endlocalis_complex=math_lib.abs(math_lib.nonRealPart(n))>1e-14ifnotis_complexthenn=math_lib.abs(n)endlocalcombination=get_divisor(n,true)localsum=to_number(0)fori=1,#combinationdolocaldivisor=to_number(1)forj=1,#(combination[i])dodivisor=divisor*to_number(combination[i][j])endsum=sum+math_lib.pow(divisor,x)endreturnsumend---------------------- 朗伯W函數 ----------------------localfunctionzexpz(z)returnmath_lib.exp(z)*zend--The derivative of z * exp(z) = exp(z) + z * exp(z)localfunctionzexpz_d(z)returnmath_lib.exp(z)+math_lib.exp(z)*zend--The second derivative of z * exp(z) = 2. * exp(z) + z * exp(z)localfunctionzexpz_dd(z)returnmath_lib.exp(z)*2+math_lib.exp(z)*zend--Determine the initial point for the root findinglocalfunctionLWInitPoint(_z,k)localz=to_number(_z)localtwo_pi_k_I=math_lib.i*2*math_lib.pi*klocalip=math_lib.log(z)+two_pi_k_I-math_lib.log(math_lib.log(z)+two_pi_k_I)--initial point coming from the general asymptotic approximationlocalp=math_lib.sqrt((math_lib.e*z+1)*2)--used when we are close to the branch cut around zero and when k=0,-1ifmath_lib.abs(-(-math_lib.exp(-1))+z)<=1then--we are close to the branch cut, the initial point must be chosen carefullyifk==0thenip=-math_lib[1]+p-1/3*math_lib.pow(p,2)+11/72*math_lib.pow(p,3)endifk==1andmath_lib.im(z)<0thenip=-math_lib[1]-p-1/3*math_lib.pow(p,2)-11/72*math_lib.pow(p,3)endifk==-1andmath_lib.im(z)>0thenip=-math_lib[1]-p-1/3*math_lib.pow(p,2)-11/72*math_lib.pow(p,3)endendifk==0andmath_lib.abs(z-0.5)<=0.5thenip=((z*7.061302897+0.1237166)*0.35173371)/((z*2+1)*0.827184+2)end-- (1,1) Pade approximant for W(0,a)ifk==-1andmath_lib.abs(z-0.5)<=0.5thenip=-(((math_lib.i*4.22096+2.2591588985)*((-math_lib.i*33.767687754-14.073271)*z-(-math_lib.i*19.071643+12.7127)*(z*2+1)))/(-(-math_lib.i*10.629721+17.23103)*(z*2+1)+2))end-- (1,1) Pade approximant for W(-1,a)returnip;endfunctionp._LambertW(_z,_k)localz=to_number(_z)localk=to_number(_k)orto_number(0)local_2=math_lib[1]*2ifmath_lib.abs(math_lib.nonRealPart(k))>1e-14thenerror("朗伯W函数的k只能是實數")endk=math_lib.re(k)--For some particular z and k W(z,k) has simple value:ifmath_lib.abs(z)==0thenreturn(k==0)and0orto_number(-math.huge)endifz==-math_lib.exp(-1)and(k==0ork==-1)thenreturn-math_lib[1]endifz==math_lib.exp(1)andk==0thenreturnmath_lib[1]+0end--Halley method beginslocalw,wprev=LWInitPoint(z,k),LWInitPoint(z,k)--intermediate values in the Halley methodlocalmaxiter=30--max number of iterations. This eliminates improbable infinite loopslocaliter=0--iteration counterlocalprec=1e-30;--difference threshold between the last two iteration results (or the iter number of iterations is taken)wprev=ww=w-_2*((zexpz(w)-z)*zexpz_d(w))/(_2*math_lib.pow(zexpz_d(w),2)-(zexpz(w)-z)*zexpz_dd(w))iter=iter+1while((math_lib.abs(w-wprev)>prec)anditer<maxiter)dowprev=ww=w-_2*((zexpz(w)-z)*zexpz_d(w))/(_2*math_lib.pow(zexpz_d(w),2)-(zexpz(w)-z)*zexpz_dd(w))iter=iter+1endreturnwend---------------------- 範數 ----------------------functionp._norm(_z,_p)localp_value=to_number(_por2)localcheck_inf=tostring(_p):match("[Ii][Nn][Ff]")localabs_p,re_p=math_lib.abs(p_value),math_lib.re(p_value)localvalue_list={}iftype(_z)==type(0)ortype(_z)==type("string")or(type(_z)==type({})and_z.numberType)thenlocalz=to_number(_z)iftype(math_lib.dot)==type(noop_func)theniftype(math_lib.elements)==type({})and#(math_lib.elements)>0thenfori=1,#(math_lib.elements)dovalue_list[#value_list+1]=math_lib.dot(z,math_lib.elements[i])endelsereturnmath_lib.abs(z)endelsereturnmath_lib.abs(z)endelseiftype(_z)==type({})and#_z>0thenfori=1,#_zdovalue_list[#value_list+1]=to_number(_z[i])orto_number(0)endendif#value_list>0thenlocalnorm_sum,norm_max,norm_min,non_zero_count=0,-1,tonumber("inf"),0fori=1,#value_listdolocalabs_value=math_lib.abs(value_list[i])ifabs_value>norm_maxthennorm_max=abs_valueendifabs_value<norm_minthennorm_min=abs_valueendifabs_value~=0thennorm_sum=math_lib.pow(abs_value,p_value)+norm_sumendifabs_value>1e-14thennon_zero_count=non_zero_count+1endendreturncheck_infand(re_p>0andnorm_maxornorm_min)or(abs_p>=1andmath_lib.pow(norm_sum,math_lib.inverse(p_value))or(abs_p~=0andnorm_sumornon_zero_count))enderror("無效的范數")endreturnp