9.2.math—Mathematicalfunctions¶Thismoduleisalwaysavailable.ItprovidesaccesstothemathematicalfunctionsdefinedbytheCstandard.Thesefunctionscannotbeusedwithcomplexnumbers;usethefunctionsofthesamenamefromthecmathmoduleifyourequiresupportforcomplexnumbers.Thedistinctionbetweenfunctionswhichsupportcomplexnumbersandthosewhichdon’tismadesincemostusersdonotwanttolearnquiteasmuchmathematicsasrequiredtounderstandcomplexnumbers.Receivinganexceptioninsteadofacomplexresultallowsearlierdetectionoftheunexpectedcomplexnumberusedasaparameter,sothattheprogrammercandeterminehowandwhyitwasgeneratedinthefirstplace.Thefollowingfunctionsareprovidedbythismodule.Exceptwhenexplicitlynotedotherwise,allreturnvaluesarefloats.9.2.1.Number-theoreticandrepresentationfunctionsmath.ceil(x)Returntheceilingofx,thesmallestintegergreaterthanorequaltox.Ifxisnotafloat,delegatestox.__ceil__(),whichshouldreturnanIntegralvalue.math.copysign(x,y)Returnafloatwiththemagnitude(absolutevalue)ofxbutthesignofy.Onplatformsthatsupportsignedzeros,copysign(1.0,-0.0)returns-1.0.math.fabs(x)Returntheabsolutevalueofx.math.factorial(x)Returnxfactorial.RaisesValueErrorifxisnotintegralorisnegative.math.floor(x)Returnthefloorofx,thelargestintegerlessthanorequaltox.Ifxisnotafloat,delegatestox.__floor__(),whichshouldreturnanIntegralvalue.math.fmod(x,y)Returnfmod(x,y),asdefinedbytheplatformClibrary.NotethatthePythonexpressionx%ymaynotreturnthesameresult.TheintentoftheCstandardisthatfmod(x,y)beexactly(mathematically;toinfiniteprecision)equaltox-n*yforsomeintegernsuchthattheresulthasthesamesignasxandmagnitudelessthanabs(y).Python’sx%yreturnsaresultwiththesignofyinstead,andmaynotbeexactlycomputableforfloatarguments.Forexample,fmod(-1e-100,1e100)is-1e-100,buttheresultofPython’s-1e-100%1e100is1e100-1e-100,whichcannotberepresentedexactlyasafloat,androundstothesurprising1e100.Forthisreason,functionfmod()isgenerallypreferredwhenworkingwithfloats,whilePython’sx%yispreferredwhenworkingwithintegers.math.frexp(x)Returnthemantissaandexponentofxasthepair(m,e).misafloatandeisanintegersuchthatx==m*2**eexactly.Ifxiszero,returns(0.0,0),otherwise0.5=abs(m)1.Thisisusedto“pickapart”theinternalrepresentationofafloatinaportableway.math.fsum(iterable)Returnanaccuratefloatingpointsumofvaluesintheiterable.Avoidslossofprecisionbytrackingmultipleintermediatepartialsums:sum([.1,.1,.1,.1,.1,.1,.1,.1,.1,.1])0.9999999999999999fsum([.1,.1,.1,.1,.1,.1,.1,.1,.1,.1])1.0Thealgorithm’saccuracydependsonIEEE-754arithmeticguaranteesandthetypicalcasewheretheroundingmodeishalf-even.Onsomenon-Windowsbuilds,theunderlyingClibraryusesextendedprecisionadditionandmayoccasionallydouble-roundanintermediatesumcausingittobeoffinitsleastsignificantbit.Forfurtherdiscussionandtwoalternativeapproaches,seetheASPNcookbookrecipesforaccuratefloatingpointsummation.math.gcd(a,b)Returnthegreatestcommondivisoroftheintegersaandb.Ifeitheraorbisnonzero,thenthevalueofgcd(a,b)isthelargestpositiveintegerthatdividesbothaandb.gcd(0,0)returns0.Newinversion3.5.math.isclose(a,b,*,rel_tol=1e-09,abs_tol=0.0)ReturnTrueifthevaluesaandbareclosetoeachotherandFalseotherwise.Whetherornottwovaluesareconsideredcloseisdeterminedaccordingtogivenabsoluteandrelativetolerances.rel_tolistherelativetolerance–itisthemaximumalloweddifferencebetweenaandb,relativetothelargerabsolutevalueofaorb.Forexample,tosetatoleranceof5%,passrel_tol=0.05.Thedefaulttoleranceis1e-09,whichassuresthatthetwovaluesarethesamewithinabout9decimaldigits.rel_tolmustbegreaterthanzero.abs_tolistheminimumabsolutetolerance–usefulforcomparisonsnearzero.abs_tolmustbeatleastzero.Ifnoerrorsoccur,theresultwillbe:abs(a-b)=max(rel_tol*max(abs(a),abs(b)),abs_tol).TheIEEE754specialvaluesofNaN,inf,and-infwillbehandledaccordingtoIEEErules.Specifically,NaNisnotconsideredclosetoanyothervalue,includingNaN.infand-infareonlyconsideredclosetothemselves.Newinversion3.5.Seealso:PEP485–Afunctionfortestingapproximateequalitymath.isfinite(x)ReturnTrueifxisneitheraninfinitynoraNaN,andFalseotherwise.(Notethat0.0isconsideredfinite.)Newinversion3.2.math.isinf(x)ReturnTrueifxisapositiveornegativeinfinity,andFalseotherwise.math.isnan(x)ReturnTrueifxisaNaN(notanumber),andFalseotherwise.math.ldexp(x,i)Returnx*(2**i).Thisisessentiallytheinverseoffunctionfrexp().math.modf(x)Returnthefractionalandintegerpartsofx.Bothresultscarrythesignofxandarefloats.math.trunc(x)ReturntheRealvaluextruncatedtoanIntegral(usuallyaninteger).Delegatestox.__trunc__().Notethatfrexp()andmodf()haveadifferentcall/returnpatternthantheirCequivalents:theytakeasingleargumentandreturnapairofvalues,ratherthanreturningtheirsecondreturnvaluethroughan‘outputparameter’(thereisnosuchthinginPython).Fortheceil(),floor(),andmodf()functions,notethatallfloating-pointnumbersofsufficientlylargemagnitudeareexactintegers.Pythonfloatstypicallycarrynomorethan53bitsofprecision(thesameastheplatformCdoubletype),inwhichcaseanyfloatxwithabs(x)=2**52necessarilyhasnofractionalbits.9.2.2.Powerandlogarithmicfunctionsmath.exp(x)Returne**x.math.expm1(x)Returne**x-1.Forsma