Forside - Universitetet i oslo€¦ · Forside UNIVERSITY OF OSLO Faculty of mathematics and...

Preview:

Citation preview

IN1900Høst2019

1/21

Forside

UNIVERSITYOFOSLOFacultyofmathematicsandnaturalsciencesExamin:IN1900ogINF1100Examdate:9.december2019Timeforexam:4timer.Attachments:ODESolver.pdfinproblem3.3Permittedaids:None.AcalculatorisavailableinInspera.Readtheentireexamsetbeforeyoustartansweringthequestions.Theexamcontainsmultiplechoicequestions,andtextquestionswhereyoushallwriteshortprogramsorreadprogramsandwritetheoutputfromtheprogram.Ifyouaremissinginformationyoucanmakeyourownreasonableassumptions,aslongastheyareinlinewiththe"nature"ofthequestion.Intextquestionsyoushouldthenspecifytheassumptionsyoumade,forinstanceincommentstothecode.

AllcodeinthequestiontextsiswritteninPython3.YoucanwriteyouranswersineitherPython2orPython3,butyoushouldavoidusingamix.Mostofthequestionsleadtoshortcodewithlittleneedforcomments,unlessyoudosomethingcomplicatedornon-standard.(whichisnotrecommended;butinthiscasethecommentsshallexplaintheideasbehindtheprogramtomakeiteasiertoevaluatethecode).Aquestionmayaskyoutowriteafunction.Amainprogramwhichcallsthefunctionisinthiscasenotneeded,unlessitisspecificallyaskedforinthequestiontext.

1.1 Hvaskrivesut?

Whatisprintedintheterminalwhenthefollowingcodeisrun?u=0foriinrange(1,5,2):u+=iprint(u)Selectonealternative:

9

Anerrormessage

4

2

Maximummarks:1

IN1900Høst2019

2/21

1.2 Hvaskrivesut?

Whatisprintedintheterminalwhenthefollowingcodeisrun?a=[]foriinrange(4):a.append([i,i+1])print(a[-1])Selectonealternative:

[4,5]

4

5

Anerrormessage

[3,4]

Maximummarks:1

1.3 Hvaskrivesut?

Whatisprintedwhenthefollowingcodeisrun?foriinrange(1,4):print(i,end='')forjinrange(i):print(j,end='')Selectonealternative:

Theargument"end=''"totheprintfunctionmakeseachwritetothescreenendwithaspace('')insteadofalinebreak.

Anerrormessage

102013012

010120123

0110201

Maximummarks:1

IN1900Høst2019

3/21

1.4 Hvaskrivesut?

Whatisprintedwhenthefollowingcodeisrun?defabsolute(x):ifx<0:return-xreturnxforx_in[-3,4,0]:print(absolute(x_),end='')Selectonealternative:

340

3-40

Anerrormessage

3-340

Maximummarks:1

IN1900Høst2019

4/21

1.5 Hvaskrivesut?

Whatisprintedwhenthefollowingcodeisrun?deffreq_lists(dna_list):n=len(dna_list[0])A=[0]*nT=[0]*nG=[0]*nC=[0]*nfordnaindna_list:index=0forbaseindna:ifbase=='A':A[index]+=1elifbase=='C':C[index]+=1elifbase=='G':G[index]+=1elifbase=='T':T[index]+=1index+=1returnA,C,G,Tdna_list=['TCGCT','GGACT','GCTGC']A,C,G,T=freq_lists(dna_list)print(G)Selectonealternative:

['G','G','G','G',0]

[0,1,2,1,0]

['T','C','G','T']

[2,1,1,1,0]

5

Maximummarks:2

1.6 Hvilkenpåstanderriktig?

Oneofthefollowingstatementsiscorrect.Whichone?Selectonealternative:

Atestfunctionmustalwaysincludeareturnstatement

Atestfunctionshouldalwaystakeatleastoneinputargument

Atestfunctioncanhavemultipleassertstatements

Atestfunctionreturns0ifthetestpasses

Maximummarks:1

IN1900Høst2019

5/21

1.7 Hvaskrivesut?

Whatisprintedintheterminalwhenthefollowingcodeisrun?defcount(dna,base):i=0forjinrange(len(dna)):ifdna[j]==base:i+=1returnideftest_count():dna='ATTTGCGGTCCAAA'success=count(dna,'A')==4msg='countreturnsthewrongnumber'assertsuccess,msgtest_count()Selectonealternative:

Success

AssertionError:countreturnsthewrongnumber

Nothingisprinted

countreturnsthewrongnumber

Maximummarks:1

IN1900Høst2019

6/21

1.8 Hvilketfunksjonskall?

Thefunctioneuler(rhs,u0,T,n)appliesEuler'smethodtosolveanordinarydifferentialequation(ODE)withrighthandsidedefinedbythefunctionrhsandinitialconditionu0,forthetimeinterval0tiT,withntimesteps:importnumpyasnp

defeuler(rhs,u0,T,n=100):t=np.linspace(0,T,n+1)dt=T/nu=np.zeros_like(t)u[0]=u0foriinrange(1,n+1):u[i]=u[i-1]+dt*rhs(u[i-1],t[i-1])returnu,tWewanttousethefunctiontosolvethedifferentialequationy'=-0.5y,y(0)=1,fortintheinterval0til5.Whichfunctioncalliscorrect?Selectonealternative:

Recallthatalambdafunctionisacompactwaytodefineafunction.Forinstance,thefollowinglinewilldefineafunctionthatreturnsx2+y2:func=lambdax,y:x**2+y**2Thislineisequivalenttothefollowingcode:deffunc(x,y):returnx**2+y**2

u,t=euler(-0.5*y,1.0,5)

u,t=euler(f=-0.5*y,1.0,5)

u,t=euler(lambday,t:-0.5*y,1.0,5)

u,t=euler(lambday:-0.5*y,1.0,5)

Maximummarks:2

IN1900Høst2019

7/21

1.9 Hvilketfunksjonskall?

Thefollowingfunctionimplementsabisectionmethodforfindingsolutionsoftheequationf(x)=0intheinterval[a,b].defbisection(f,a,b,eps=1e-5):fa=f(a)iffa*f(b)>0:print(f'Nouniquerootin[{a},{b}]')returnNonewhileb-a>eps:m=(a+b)/2.0fm=f(m)iffa*fm<=0:b=m#rootisinlefthalfof[a,b]else:a=m#rootisinrighthalfof[a,b]fa=fmreturnmWewanttousethefunctiontofindasolutionoftheequation

intheinterval[-10,10].Whichfunctioncalliscorrect?Selectonealternative:

Recallthatalambdafunctionisacompactwaytodefineafunction.Forinstance,thefollowinglinewilldefineafunctionthatreturnsx2+y2:func=lambdax,y:x**2+y**2Thislineisequivalenttothefollowingcode:deffunc(x,y):returnx**2+y**2

x=bisection(lambdax:x**3+2*x-1,-10,10)

x=bisection(f(x)=x**3+2*x-1,-10,10,eps=1e-5)

x=bisection(x**3+2*x-1,-10,10,eps=1e-5)

x=bisection(eval('x**3+2*x-1'),-10,10)

Maximummarks:2

IN1900Høst2019

8/21

1.10 Hvorfeilerkoden?

Inwhichlinewillthiscodestopandwriteanerrormessage?a=[[4,5],[0,1],2,[2,0.5],4,3,[5,6,7]]b=[]foreina:s=0fornumberine:s+=numberb.append(s)print(b)print(b)Selectonealternative:

s+=number

b.append(s)

foreina:

a=[[4,5],[0,1],2,[2,0.5],4,3,[5,6,7]]

fornumberine:

Maximummarks:2

IN1900Høst2019

9/21

1.11 Hvaskrivesut?

Thefileformula_cml.pycontainsthefollowingcode:importsysfrommathimport*try:formula=sys.argv[1]x=[float(x_)forx_insys.argv[2:]]exceptIndexError:print('Missingcommandlineargument')exit()code=f"""deff(x):return{formula}"""

try:exec(code)except:print('Somethingwronginformula')exit()forx_inx:print(f(x_),end='')Whatisprintedwhentheprogramisruninthefollowingway?Terminal>pythonformula_cml.py2*x**2-313Fillinyouranswerhere

Words:0

Maximummarks:2

IN1900Høst2019

10/21

1.12 Hvaskrivesut?

Thefilestars.txtcontainsthefollowing:NamedistancebrightnessluminosityAlpha_Centauri_A4.30.261.56Alpha_Centauri_B4.30.0770.45Alpha_Centauri_C4.20.000010.00006Sirius_A8.61.0023.6Therearenoblanklinesinthefile.Whatisprintedwhenthefollowingcodeisrun?stars_data={}

withopen('stars.txt')asinfile:infile.readline()forlineininfile:w=line.split()data={'dist':w[1],'bright':w[2],'lum':w[3]}stars_data[w[0]]=dataprint(len(stars_data),stars_data['Sirius_A']['bright'])Fillinyouranswerhere

Words:0

Maximummarks:2

IN1900Høst2019

11/21

2.1 Funksjonavtovariable

Writeapythonfunctionf(x,y)thatreturnsthevalueofthemathematicalexpression

Fillinyouranswerhere

Maximummarks:3

1

IN1900Høst2019

12/21

2.2 Numeriskderivasjon

Thederivativeofamathematicalfunctionf(x)canbeapproximatedwiththemidpointformula

forasmallnumberh.WriteaPythonfunctionmidpoint(f,x,h),whichusesthisformulatoestimatethederivativeofafunctionfinthepointx.Thefunctionshallreturnthefunctionvaluef(x)andtheestimatedderivative.TheargumentfcanbeanarbitrarymathematicalfunctionimplementedasaPythonfunction,whichtakesoneinputargumentandreturnsonevalue.Includealinewhereyoucallthefunctiontoestimatethederivativeofcos(x)inthepointx=0,forh=0.001.Fillinyouranswerhere

Maximummarks:5

1

IN1900Høst2019

13/21

2.3 Implementasjonavensum

WriteaPythonfunctioncos_approx(x,n)whichcomputesthesum

andreturnsthevalue.xcanbeadecimalnumber(float)oraNumpy-arrayofdecimalnumbers,whilenisapositiveinteger.Recallthatk!isthefactorialofk.Includenecessaryimports.Fillinyouranswerhere

Maximummarks:5

1

IN1900Høst2019

14/21

2.4 Lesingavfil

Thefileconstants.txthasthefollowingcontents:nameofconstantvaluedimension------------------------------------------------------------lightspeed299792458.0m/sgravitationalconstant6.67259e-11m**3/kg/s**2Planckconstant6.6260755e-34J*selementarycharge1.60217733e-19CAvogadronumber6.0221367e231/molBoltzmannconstant1.380658e-23J/Kelectronmass9.1093897e-31kgprotonmass1.6726231e-27kgThefilecontainsnoblanklines.WriteaPythonprogramthatreadsthisfileandstoresitscontentsinadictionary.Thekeysofthedictionaryshallbethenameoftheconstant(fromthecolumn"nameofconstant"),andthevalueshallbealistortupleoflengthtwothatcontainsthenumericvalueoftheconstant(column"value")anditsphysicalunits(column"dimension").Hint:ThePythonmethodjoinisusedforjoiningalistofstringsintoasinglestring.Asanexample,thecodestring_list=['Hello','world']hello=''.join(string_list)willresultinastringhellohavingthevalue"Helloworld".Fillinyouranswerhere

Maximummarks:6

1

IN1900Høst2019

15/21

2.5 Dictionaryogsum

Apolynomialp(x)canberepresentedasadictionary,sothatthekeysofthepolynomialaretheexponentsandthevaluesarethecoefficientsinfrontofeachterm.Forinstance,thepolynomial

canberepresentedasthedictionaryp={0:1,2:-2,4:3,5:1}WriteaPythonfunctionpoly_eval(p,x),whichevalueatessuchapolynomialpforagivenx,andreturnsitsvalue.Fillinyouranswerhere

Maximummarks:5

1

IN1900Høst2019

16/21

2.6 Derivasjonavpolynom

Ageneralpolynomialcanbewrittenontheform

wherecjareconstantcoefficients.

Thederivativeofsuchapolynomialisgivenby

WriteaPythonfunctionpoly_diff(p)thatcalculatesthederivativeofageneralpolynomialp.Theargumentpisadictionaryrepresentationofapolynomial,asdefinedinthepreviousquestion.Thefunctionshallreturnadictionaryrepresentingthederivativeofp.Fillinyouranswerhere

Maximummarks:5

1

IN1900Høst2019

17/21

3.1 Klasseforenfunksjon

WriteaPythonclassFwhichimplementsthefunction

Theparametersa,b,andcshallbeattributes,andtheclassshallbepossibletouseinthefollowingway

f=F(a=1.0,b=2.0,c=0.0)x=2.0print(f(x))#printsthefunctionvalue(8.0)Fillinyouranswerhere

Maximummarks:5

1

IN1900Høst2019

18/21

3.2 ODE-løser,funksjon

WriteaPythonfunctionheun3(f,U0,T,n),whichusesHeun's3.ordermethodtosolveanordinarydifferentialequation(ODE)givenby:

Heun's3.ordermethodisgivenby

Theargumentstothefunctionshallbeacallablefunctionf,whichdefinestherighthandsideoftheODE,theinitialconditionU0,theend-timeT,andthenumberoftimestepsn.Thefunctionshallreturntwonumpy-arraysuandt,whereucontainsthesolutionandtcontainsthetimepointswherewehaveapproximatedthesolution.InthisquestionyoucanassumethatwesolveascalarODE,wherethesolutionhasonlyonecomponent.Thesolutionarrayushouldthereforebeaone-dimensionalarray.Includenecessaryimports.Fillinyouranswerhere

Maximummarks:5

1

IN1900Høst2019

19/21

3.3 ODESolver,arv

Implementthemethodfromthepreviousquestion(Heun's3.ordermethod)asasubclassHeun3(ODESolver).ThebaseclassODESolverisdefinedintheattachedfile.Useinheritancetoreuseasmuchcodeaspossiblefromthebaseclass.TheclassHeun3mustsupportthefollowinguse:fromnumpyimport*fromODESolverimport*rhs=lambdau,t:-0.5*usolver=Heun3(rhs)solver.set_initial_condition(1.0)time=numpy.linspace(0,10,101)u,t=solver.solve(time)Fillinyouranswerhere

Maximummarks:5

1

IN1900Høst2019

20/21

3.4 Logistiskvekst

Themodelforlogisticgrowthisdefinedbythefollowingordinarydifferentialequation(ODE):

Themodeldescribesgrowthofapopulationinanenvironmentwithlimitedresources,whereuisthesizeofthepopulation,tistime,andaandRareconstantmodelparameters.WriteaPythonfunctionrhs(u,t)thatdefinestherighthandsideoftheequation.Theparameterscanbelocalvariablesinthefunction,withvaluesa=1andR=50.WritecodeforsolvingtheequationwiththeHeun3-klassfromthepreviousquestion.Theinitialconditionshallbeu0=0.1,thetimeintervalfromt=0tot=20,andyoushalluse201timestepsincludingtheendpoints(dt=0.1).Fillinyouranswerhere

Maximummarks:5

1

IN1900Høst2019

21/21

3.5 SEIS-modell

Thisquestionpresentsaso-calledSEIS-modelformodelinginfectiousdiseases.ThemodelisamodificationoftheclassicalSIR-model,wherethepopulationisdividedinthreegroups:thosewhocanbeinfected(S),thosewhoareinfectedbuthavenotyetdevelopedthedisease,andcannotinfectothers(E),andthosethataresickandcaninfectothers(I).Thereisnoimmunityinthemodel,sothosethatrecoverfromthediseasereturntotheS-category.LetS(t),E(t),andI(t)bethenumberofpeopleineachcategory(measuredinmillions).ThefollowingsystemofdifferentialequationsdescribeshowS(t),E(t),andI(t)evolveoveratimeinterval[0,T]:

Attimet=0wehavetheintitialconditionsS(0)=S0,E(0)=E0,I(0)=0.Thefunctionp(t)andtheconstantsqandrareassumedtobeknown.Allconstantsandfunctionsare>0.WriteaPython-functionSEIS(S0,E0,p,q,r,T),whichtakesinitialvaluesS0,E0,thefunctionp(t),parametersq,r,andtheend-timeTasinputarguments.ThefunctionshallsolvetheequationsoftheSEIS-modelandreturnthesolution.UsetheHeun3classfromthepreviousquestiontosolvethedifferentialequations.Letthetimebegivenindays.Usetentimestepsperday,sothatthetotalnumberoftimestepsforasimulationovertheinterval[0,T]is10T+1.ThefunctionSEISshallreturn4arrays:t,whichcontainsthetimepointstkwherethenumericalsolutioniscalculated,S,whichcontainsS(0),S(t1),...S(tn),E,whichcontainsE(0),E(t1),...E(tn),I,whichcontainsI(0),I(t1),...I(tn).Wewanttosolvethemodelwiththefollowingparameters;S0=4.0,E0=0.2,q=r=0.1,andp(t)=0.0233(constant).WritethecodetocallthefunctionwiththegivenparametersandT=100.AlsoincludecodetoplotS(t),E(t)andI(t)inthesamewindow,withalegendforeachcurve.Fillinyouranswerhere

Maximummarks:8

1

Question 21Attached

import numpy as np

class ODESolver:"""Superclass for numerical methods solving scalar and vector ODEs

du/dt = f(u, t)

Attributes:t: array of time valuesu: array of solution values (at time points t)k: step number of the most recently computed solutionf: callable object implementing f(u, t)"""def __init__(self, f):

if not callable(f):raise TypeError('f is %s, not a function' % type(f))

self.f = lambda u, t: np.asarray(f(u, t), float)

def set_initial_condition(self, U0):if isinstance(U0, (float,int)): # scalar ODE

self.neq = 1U0 = float(U0)

else: # system of ODEsU0 = np.asarray(U0) # (assume U0 is sequence)self.neq = U0.size

self.U0 = U0

def advance(self):"""Advance solution one time step."""raise NotImplementedError

def solve(self, time_points):"""Compute solution u for t values in the list/array"""self.t = np.asarray(time_points)n = self.t.sizeif self.neq == 1: # scalar ODEs

self.u = np.zeros(n)else: # systems of ODEs

self.u = np.zeros((n,self.neq))

# Assume that self.t[0] corresponds to self.U0self.u[0] = self.U0

# Time loopfor k in range(n-1):

self.k = kself.u[k+1] = self.advance()

return self.u, self.t

class ForwardEuler(ODESolver):def advance(self):

u, f, k, t = self.u, self.f, self.k, self.tdt = t[k+1] - t[k]u_new = u[k] + dt*f(u[k], t[k])return u_new

1

Recommended