Tải bản đầy đủ - 0 (trang)
Variables, Types, and Operations

Variables, Types, and Operations

Tải bản đầy đủ - 0trang

Chapter2.Variables,Types,and

Operations

Juliaisanoptionallytypedlanguage,whichmeansthattheusercanchoosetospecifythe

typeofargumentspassedtoafunctionandthetypeofvariablesusedinsideafunction.

Julia’stypesystemisthekeyforitsperformance;understandingitwellisimportant,andit

canpaytousetypeannotations,notonlyfordocumentationortooling,butalsofor

executionspeed.Thischapterdiscussestherealmofelementarybuilt-intypesinJulia,the

operationsthatcanbeperformedonthemaswellastheimportantconceptsoftypesand

scope.

Thefollowingtopicsarecoveredinthischapter:

Variables,namingconventions,andcomments

Types

Integers

Floatingpointnumbers

Elementarymathematicalfunctionsandoperations

Rationalandcomplexnumbers

Characters

Strings

Regularexpressions

Rangesandarrays

Datesandtimes

Scopeandconstants

YouwillneedtofollowalongbytypingintheexamplesintheREPL,orexecutingthe

codesnippetsinthecodefilesofthischapter.



Variables,namingconventions,and

comments

Dataisstoredinvaluessuchas1,3.14,"Julia",andeveryvaluehasatype,forexample,

thetypeof3.14isFloat64.Someotherexamplesofelementaryvaluesandtheirdata

typesare42oftheInt64type,trueandfalseoftheBooltype,and'X'oftheChartype.

Julia,unlikemanymodernprogramminglanguages,differentiatesbetweensingle

charactersandstrings.Stringscancontainanynumberofcharactersandarespecified

usingdoublequotes,andsinglequotesareonlyusedforcharacterliterals.Variablesare

thenamesthatareboundtovaluesbyassignments,suchasx=42.Theyhavethetypeof

thevaluetheycontain(orreference);thistypeisgivenbythetypeoffunction.For

example,typeof(x)returnsInt64.

Thetypeofavariablecanchange,becauseputtingx="IamJulia"nowresultsin

typeof(x)returningASCIIString.InJulia,wedon’thavetodeclareavariable(that

indicatesitstype)suchasinCorJavaforinstance,butavariablemustbeinitialized(that

isboundtoavalue),sothatJuliacandeduceitstype.

julia>y=7

7

typeof(y)#Int64

julia>y+z

ERROR:znotdefined



Intheprecedingexample,zwasnotassignedavaluebeforeusingit,sowegotanerror.

Bycombiningvariablesthroughoperatorsandfunctionssuchasthe+operator(asinthe

precedingexample),wegetexpressions.Anexpressionalwaysresultsinanewvalue

aftercomputation.Contrarytomanyotherlanguages,everythinginJuliaisanexpression,

soitreturnsavalue.That’swhyworkinginaREPLissogreatbecauseyoucanseethe

valuesateachstep.

Thetypeofvariablesdetermineswhatyoucandowiththem,thatis,theoperatorswith

whichtheycanbecombined,inthissense,Juliaisastrongly-typedlanguage.Inthe

followingexample,xisstillaStringvalue,soitcan’tbesummedwithywhichisoftype

Int64,butifwegivexafloatvalue,thesumcanbecalculated,asshowninthefollowing

example:

julia>x+y

ERROR:`+`hasnomethodmatching+(::ASCIIString,::Int64)

julia>x=3.5;x+y

10.5



Here,thesemicolon(;)endsthefirstexpressionandsuppressesitsoutput.Namesofthe

variablesarecasesensitive.Byconvention,lowercaseisusedwithmultiplewords

separatedbyanunderscore.Theystartwithaletterandafterthat,youcanuseletters,

digits,underscores,andexclamationpoints.YoucanalsouseUnicodecharacters.Use

clear,short,andtothepointnames.Herearesomevalidvariablenames:mass,



moon_velocity,current_time,pos3,andω1.However,thelasttwoarenotvery

descriptive,andtheycouldbetterbereplacedwith,forexample,particle_positionand

particle_ang_velocity.



Alineofcodeprecededbyahashsign(#)isacomment,aswecanseeinthefollowing

example:

#Calculatethegravitationalaccelerationgrav_acc:

gc=6.67e-11#gravitationalconstantinm3/kgs2

mass_earth=5.98e24#inkg

radius_earth=6378100#inm

grav_acc=gc*mass_earth/radius_earth^2#9.8049m/s2



Multi-linecommentsarehelpfulforwritingcommentsthatspanacrossmultiplelinesor

commentingoutcode.Juliawilltreatallthetextbetween#=and=#asacomment.For

printingoutvalues,usetheprintorprintlnfunctionsasfollows:

julia>print(x)

3.5



Ifyouwantyourprintedoutputtobeincolor,useprint_with_color(:red,"Ilove

Julia!")thatreturnstheargumentstringinthecolorindicatedbythefirstargument.

Thetermobject(orinstance)isfrequentlyusedwhendealingwithvariablesofmore

complextypes.However,wewillseethatwhendoingactionsonobjects,Juliauses

functionalsemantics.Wewriteaction(object)insteadofobject.action(),aswedoin

moreobject-orientedlanguagessuchasJavaorC#.

InaREPL,thevalueofthelastexpressionisautomaticallydisplayedeachtimea

statementisevaluated(unlessitendswitha;sign).Inastandalonescript,Juliawillnot

displayanythingunlessthescriptspecificallyinstructsitto.Thisisachievedwithaprint

orprintlnstatement.TodisplayanyobjectinthewaytheREPLdoesincode,use

display(object).



Types

Julia’stypesystemisunique.Juliabehavesasadynamically-typedlanguage(suchas

Pythonforinstance)mostofthetime.Thismeansthatavariableboundtoanintegerat

onepointmightlaterbeboundtoastring.Forexample,considerthefollowing:

julia>x=10

10

julia>x="hello"

"hello"



However,onecan,optionally,addtypeinformationtoavariable.Thiscausesthevariable

toonlyacceptvaluesthatmatchthatspecifictype.Thisisdonethroughatypeannotation.

Forinstance,declaringx::ASCIIStringimpliesthatonlystringscanbeboundtox;in

general,itlookslikevar::TypeName.Theseareusedmostoftentoqualifytheargumentsa

functioncantake.Theextratypeinformationisusefulfordocumentingthecode,and

oftenallowstheJITcompilertogeneratebetteroptimizednativecode.Italsoallowsthe

developmentenvironmentstogivemoresupport,andcodetoolssuchasalinterthatcan

checkyourcodeforpossiblewrongtypeuse.

Hereisanexample:afunctionwiththecalc_positionnamedefinedasthefunction

calc_position(time::Float64),indicatesthatthisfunctiontakesoneargumentnamed

timeofthetypeFloat64.

Juliausesthesamesyntaxfortypeassertionsthatareusedtocheckwhetheravariableor

anexpressionhasaspecifictype.Writing(expr)::TypeNameraisesanerrorifexprisnot

oftherequiredtype.Forinstance,considerthefollowing:

julia>(2+3)::ASCIIString

ERROR:type:typeassert:expectedASCIIString,gotInt64



Noticethatthetypecomesafterthevariablename,unlikeinmostotherlanguages.In

general,thetypeofavariablecanchangeinJulia,butthisisdetrimentaltoperformance.

Forutmostperformance,youneedtowritetype-stablecode.Codeistype-stableifthe

typeofeveryvariabledoesnotvaryovertime.Carefullythinkingintermsofthetypesof

variablesisusefulinavoidingperformancebottlenecks.Addingtypeannotationsto

variablesupdatedintheinnerloopofacriticalregionofcodecanleadtodrastic

improvementsintheperformancebyhelpingtheJITcompilerremovesometype

checking.Toseeanexcellentexamplewherethisisimportant,readthearticleavailableat

http://www.johnmyleswhite.com/notebook/2013/12/06/writing-type-stable-code-in-julia/.

Alotoftypesexist,infact,awholetypehierarchyisbuiltininJulia.Ifyoudon’tspecify

thetypeofafunctionargument,ithasthetypeAny,whichiseffectivelytherootorparent

ofalltypes.EveryobjectisatleastoftheuniversaltypeAny.Attheotherendofthe

spectrum,thereistypeNonethathasnovalues.Noobjectcanhavethistype,butitisa

subtypeofeveryothertype.Whilerunningthecode,Juliawillinferthetypeofthe

parameterspassedinafunction,andwiththisinformation,itwillgenerateoptimal

machinecode.



Youcandefineyourowncustomtypesaswell,forinstance,aPersontype.By

convention,thenamesoftypesbeginwithacapitalletter,andifnecessary,theword

separationisshownwithCamelCase,suchasBigFloatorAbstractArray.

Ifxisavariable,thentypeof(x)givesitstype,andisa(x,T)testswhetherxisoftype

T.Forexample,isa("ABC",String)returnstrue,andisa(1,Bool)returnsfalse.

EverythinginJuliahasatype,includingtypesthemselves,whichareoftypeDataType:

typeof(Int64)returnsDataType.ConversionofavariablevartoatypeType1canbe

doneusingthetypename(lower-cased)asafunctiontype1(var),forexample,

int64(3.14)returns3.

However,thisraisesanerroriftypeconversionisimpossibleasfollows:

julia>int64("hello")

ERROR:invalidbase10digit'h'in"hello"



Integers

JuliaofferssupportforintegernumbersrangingfromtypesInt8toInt128,with8to128

representingthenumberofbitsused,andwithunsignedvariantswithaUprefix,suchas

UInt8.Thedefaulttype(whichcanalsobeusedasInt)isInt32orInt64dependingon

thetargetmachinearchitecture.ThebitwidthisgivenbythevariableWORD_SIZE.The

numberofbitsusedbytheintegeraffectsthemaximumandminimumvaluethisinteger

canhave.Theminimumandmaximumvaluesaregivenbythefunctionstypemin()and

typemax()respectively,forexample,typemax(Int16)returns32767.

Ifyoutrytostoreanumberlargerthanthatallowedbytypemax,overflowoccurs.For

example:

julia>typemax(Int)

9223372036854775807#mightbedifferenton32bitplatform

julia>ans+1

-9223372036854775808



Overflowcheckingisnotautomatic,soanexplicitcheck(forexample,theresulthasthe

wrongsign)isneededwhenthiscanoccur.Integerscanalsobewritteninbinary(0b),

octal(0o),andhexadecimal(0x)format.

Forcomputationsneedingarbitrary-precisionintegers,JuliahasaBigInttype.These

valuescanbeconstructedasBigInt("number"),andsupportthesameoperatorsas

normalintegers.Conversionsbetweennumerictypesareautomatic,butnotbetweenthe

primitivetypesandtheBig-types.Thenormaloperationsofaddition(+),subtraction(-),

andmultiplication(*)applyforintegers.Adivision(/)alwaysgivesafloatingpoint

number.Ifyouonlywantintegerdivisorandremainder,usedivandrem.Thesymbol^is

usedtoobtainthepowerofanumber.Thelogicalvalues,trueandfalse,oftypeBool

arealsointegerswith8bits.0amountstofalse,and1(infact,alsoallvaluesotherthan

0)totrue;forexample,bool(-56)returnstrue.Negationcanbedonewiththe!

operator;forexample,!trueisfalse.Comparingnumberswith==(equal),!=or

returnaBoolvalue,andcomparisonscanbechainedafteroneanother(asin0


Floatingpointnumbers

FloatingpointnumbersfollowtheIEEE754standardandrepresentnumberswitha

decimalpointsuchas3.14oranexponentnotation4e-14,andcomeinthetypesFloat16

uptoFloat64,thelastoneusedfordoubleprecision.

SingleprecisionisachievedthroughtheuseoftheFloat32type.Singleprecisionfloat

literalsmustbewritteninscientificnotation,suchas3.14f0,butwithf,whereone

normallyusese.Thatis,2.5f2indicates2.5*10^2withsingleprecision,while2.5e2

indicates2.5*10^2indoubleprecision.JuliaalsohasaBigFloattypeforarbitraryprecisionfloatingnumbers’computations.

Abuilt-intypepromotionsystemtakescareofallthenumerictypesthatcanwork

togetherseamlessly,sothatthereisnoexplicitconversionneeded.Specialvaluesexist:

Infand-Infforinfinity,andNaNisusedfor“notanumber”-valuessuchastheresultof

0/0orInf–Inf.

Floatingpointarithmeticinallprogramminglanguagesisoftenasourceofsubtlebugs

andcounter-intuitivebehavior.Forinstance:

julia>0.1+0.2

0.30000000000000000004



Thishappensbecauseofthewaythefloatingpointnumbersarestoredinternally.Most

numberscannotbestoredinternallywithafinitenumberofbits,suchas1/3hasnofinite

representationinbase10.Thecomputerwillchoosetheclosestnumberitcanrepresent,

introducingasmallroundofferror.Theseerrorsmightaccumulateoverthecourseof

longcomputations,creatingsubtleproblems.

Maybethemostimportantconsequenceofthisistheneedtoavoidusingequalitywhen

comparingfloatingpointnumbers:

julia>0.1+0.2==0.3

false



Abettersolutionistouse>=or<=comparisonsinBooleanteststhatinvolvefloatingpoint

numbers,whereverpossible.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Variables, Types, and Operations

Tải bản đầy đủ ngay(0 tr)

×