All exercises. Øyvind Ryan
|
|
|
- Per Pedersen
- 9 år siden
- Visninger:
Transkript
1 All exercises Øyvind Ryan 19. februar 2013
2 1. Bruk Matlab til å løse oppgave?? og?? ovenfor. 2. Vi har to vektorer a = (1, 2,3) og b = (2,2, 4). Sjekk at lengdene til vektorene kan finnes ved kommandoene» norm(a) og» norm(b). Forklar at du kan finne vinkelen mellom vektorene ved kommandoen acos(dot(a,b)/(norm(a)*norm(b))) Finn vinkelen. 3. Bruk Matlab til å løse oppgave??. 4. Bruk Matlab til å løse oppgavene Skriv inn matrisene og A = B = i Matlab og gjennomfør operasjonene» C=[A,B],» C(2,4),» C(:,[2 3]),» C([1 3],3:5). % Oppgave A=[2,-3,1;4,1,-5;1,2,-1]; B=[-1,3,2;4,5,1;0,2,-1]; C=[A,B] C(2,4) C(:,[2 3]) C([1 3],3:5) 6. Bruk matrisen C fra forrige oppgave. Undersøk hva som skjer med matrisen når du skriver» C(:,3)=2*C(:,3) og» C([1,3],:)=4*C([1,3],:). % Oppgave A=[2,-3,1;4,1,-5;1,2,-1]; B=[-1,3,2;4,5,1;0,2,-1]; C(:,3)=2*C(:,3) C([1,3],:)=4*C([1,3],:) 2
3 7. Undersøk hva kommandoen» [A;B] gjør når A og B er to matriser. % Oppgave A=[2,-3,1;4,1,-5;1,2,-1]; B=[-1,3,2;4,5,1;0,2,-1]; [A;B] 8. Bruk Matlab til å løse oppgavene Definer to matriser A=[2 4 6;1 3 5;7 8 9]; B=[1 4;2 5;3 6]; i Matlab. a. Regn ut de to produktene A*B(:,1) A*B(:,2) b. Regn på samme måte ut de tre produktene A(1,:)*B A(2,:)*B A(3,:)*B Hvordan kan du bruke resultatene fra kallene i a) og b) som kontroller på utregningen av A*B med Matlab? La A = og B = Bruk Matlab til å regne ut; A T, B T, (AB) T, A T B T, B T A T, A 1, B 1, (AB) 1, A 1 B 1, B 1 A 1. Blir noen av resultatene like? Hvilke av punktene i Setning?? kan brukes til å forklare disse likhetene? % Oppgave 2.1 A=[ ; ; ; ]; B=[ ; ; ; ]; A 3
4 B (A*B) A *B B *A inv(a) inv(b) inv(a*b) inv(a)*inv(b) inv(b)*inv(a) 11. Bruk Matlab til å finne den inverse matrisen til A i oppgave Be Matlab om å invertere matrisene i oppgave 3. Hva skjer i de tilfellene matrisen ikke er inverterbar? 13. Bruk Matlab til å regne ut determinantene i oppgavene 1, 10, og Bruk Matlab til å tegne kurvene: % Oppgave a) t=linspace(0,6*pi,100); plot(t.*cos(t),t.*sin(t)); % Oppgave b) t=linspace(0,2*pi,100); plot(5*cos(t),3*sin(t)); % Oppgave c) t=linspace(0,2*pi,100); plot(sin(2*t).*cos(t),sin(2*t).*sin(t)); % Oppgave d) t=linspace(0,6*pi,100); plot3(t.*cos(t),t.*sin(t),t); % Oppgave e) t=linspace(-20,20,400); plot3(t,sin(t),cos(t)); a. r(t) = t cos t i + t sin t j, t [0,6π] b. r(t) = 5cos t i + 3sin t j, t [0,2π] 4
5 c. r(t) = sin(2t)cos t i + sin(2t)sin t j, t [0,2π] d. r(t) = t cos t i + t sin t j + t k, t [0,6π] e. r(t) = t i + sin t j + cos t k, t [ 20,20] 15. Bruk Matlab til å tegne kurven r(t) i eksempel 9. Velg m = 1, g = 9.8 og eksperimenter med forskjellige verdier for k, u 1 og u 2. Løsningsforslag: % Oppgave t=linspace(0,200,1000); m=1; g=9.8; k=0.5; u1=0.2; u2=0.4; f1=(m*u1/k)*(1-exp(-k*t/m)); f2=(-m*g*t/k)+(m*u2/k + m*m*g/(k*k))*(1-exp(-k*t/m)) plot(f1,f2); 16. Vi har r(t) = (2cos t, 2sin t, 2sin t). a. Finn hastigheten, farten og akselerasjonen. Svar: v(t) = ( 2sin t, 2cos t, 2cos t) v(t) = 2 a(t) = r(t) Løsningsforslag: Vi regner ut v(t) = r (t) = ( 2sin t, 2cos t, 2cos t) v(t) = v(t) = 4sin 2 t + 2cos 2 t + 2cos 2 t = 2 a(t) = v (t) = ( 2cos t, 2sin t, 2sin t) b. Finn buelengden fra t = 0 til t = 2π. Svar: 4π Løsningsforslag: L(0,2π) = 2π 0 v(t)dt = 5 2π 0 2dt = 4π.
6 c. Vis at kurven ligger på en kuleflate med sentrum i origo. Svar: x 2 + y 2 + z 2 = 4 Løsningsforslag: En kule med sentrum i origo er beskrevet ved at x 2 +y 2 + z 2 = r 2, der r er kuleradien. Vi har at x 2 + y 2 + z 2 = 4cos 2 t + 2sin2t + 2sin 2 t = 4cos 2 t + 4sin 2 t = 4 = 2 2, og derfor ligger kurven på en kule om origo med radius 2. d. Vis at kurven ligger i planet y z = 0. Løsningsforslag: Vi har at y z = 2sin t 2sin t = 0, og derfor ligger kurven i det gitte planet. e. Hva slags kurve fremstiller r? Bruk Matlab til å tegne kurven. Svar: En sirkel med radius 2 om origo i planet y-z=0. Løsningsforslag: Kurven beskriver en sirkel med radius 2, på grunn av c), d), og det faktum at skjæringen mellom en kule med senter i origo og et plan gjennom origo er en sirkel med samme radius som kula. % Oppgave e) t=linspace(0,2*pi,100); plot3(2*cos(t),sqrt(2)*sin(t),sqrt(2)*sin(t)); 17. Vi har r(t) = (t cos t, t sin t, t) % Oppgave b) quad(@(x)sqrt(2+t.^2),0,2*pi) a. Finn hastigheten, farten og akselerasjonen. Svar: v(t) = (cos t t sin t,sin t + t cos t,1) v(t) = 2 + t 2 b. Vis at buelengden fra t = 0 til t = 2π er 2π t 2 dt. Bruk numerisk integrasjon til å beregne dette integralet. Svar: c. Løs integralet i b) ved regning. Bruk substitusjonen t = eu e u 2. Svar: π 2 + 4π 2 + ln( 2π + 2π 2 + 1) 6
7 18. Avstanden mellom det stedet der bakhjulet til en sykkel berører bakken, og det stedet der forhjulet berører bakken, er 1 meter. Når vi sykler, etterlater både forhjulet og bakhjulet et spor i bakken. a. Anta at sporet bakhjulet etterlater seg, er gitt ved r 1 (t). Vis at sporet forhjulet etterlater seg, har parametrisering r 2 (t) = r 1 (t) + T 1 (t), der T 1 (t) er enhetstangentvektoren til r 1 (t). Løsningsforslag: Siden fartsretningen til bakhjulet alltid er retningen mot forhjulet, så vil v 1 (t) ha samme retning som r 2 (t) r 1 (t). Fra oppgaveteksten har vi at r 2 (t) r 1 (t) har lengde 1, så denne er dermed en enhetsvektor i fartsretningen, som også er definisjonen på T 1 (t). Altså er T 1 (t) = r 2 (t) r 1 (t), slik at r 2 (t) = r 1 (t) + T 1 (t). b. Anta at bakhjulet følger kurven r 1 (t) = (t,sin t). Finn parametriseringen r 2 (t) til kurven som forhjulet følger. 1 Svar: r 2 (t) = (t +,sin t + cos t ) 1+cos 2 t 1+cos 2 t Løsningsforslag: Vi antar at r 1 (t) = (t,sin t), og får da at v 1 (t) = (1,cos t) v(t) = 1 + cos 2 t ( ) 1 T 1 (t) = 1 + cos 2 t, cos t ( 1 + cos 2 t r 2 (t) = r 1 (t) + T 1 (t) = t cos 2 t,sin t + ) cos t. 1 + cos 2 t c. Bruk Matlab til å tegne kurvene r 1 og r 2 i samme koordinatsystem. % Oppgave c) t = 0:0.05:10; plot(t,sin(t), k-,... t + 1./sqrt(1+cos(t).^2),sin(t) + cos(t)./sqrt(1+cos(t).^2), k+ ); leg( bakhjul, forhjul ); axis( equal ); 7
8 d. Figuren ovenfor viser sporene etter en sykkel som har vinglet forbi. Kjørte sykkelen fra venstre mot høyre eller i motsatt retning? Svar: Fra venstre mot høyre Løsningsforslag: Sykkelen kjører fra venstre mot høyre, siden plottet faller sammen med det vi tegnet i c). 19. Bruk Matlab til å tegne kurvene r 1 (t) = (t, t 2,sin t) og r 2 (t) = (sin 2 t,cos 2 t,e t ). Vri på koordinatsystemet for å se kurvene best mulig. % Oppgave 5.2 t=linspace(0,50,1000); x1=t; y1=t.^2; z1=sin(t); x2=sin(t).^2; y2=cos(t).^2; z2=exp(-t); plot3(x1,y1,z1) figure(2) plot3(x2,y2,z2) 20. Bruk kommandoen plot3 til å lage en tredimensjonal strektegning av en terning. % Oppgave 5.3 a=[ ]; b=[ ]; c=[ ]; plot3(a,b,c) axis( equal ) 8
9 21. I denne oppgaven skal vi se nærmere på vektorfeltet i eksempel 3. F(x, y) = y x 2 + y 2 i + x x 2 + y 2 j a. La φ 1 (x, y) = arctan y x +C der C er en konstant. Vis at φ 1(x, y) = F(x, y) når x 0. Løsningsforslag: Med φ 1 (x, y) = arctan y x +C får vi φ 1 (x, y) = y x ( y ) 2 i + x 1 x 1 + ( y x ) 2 j = y x 2 + y 2 i + x x 2 j = F(x, y). + y 2 b. Regn ut C F dr der C er en glatt kurve som ligger til høyre for y-aksen og som starter i punktet (1, 1) og er i (3,3). π Svar: 2 Løsningsforslag: Siden F har potensialfunksjonen φ 1, og denne er definert til høyre for y-aksen, så har vi at F dr = φ 1 (3,3) φ 1 (1, 1) = arctan(1) arctan( 1) C = π ( 4 π ) = π 4 2. c. La φ 2 (x, y) = arctan x y + C der C er en konstant. Vis at φ 2(x, y) = F(x, y) når y 0. Løsningsforslag: Med φ 2 (x, y) = arctan x y +C får vi φ 2 (x, y) = 1 + Koden blir 1 y ( x y ) 2 i x y 2 ( x y ) 2 j = y x 2 + y 2 i + x x 2 j = F(x, y). + y 2 d. Bruk Matlab eller en lommeregner til å tegne grafene til φ 1 og φ 2 (husk at ar ct an heter atan i Matlab). e. Finn sammenhengen mellom arctan y x og arctan x y (det kan lønne seg å se på hver kvadrant { for seg). arctan Svar: arctan y x x = y + π 2 når (x, y) ligger i 1. og 3. kvadrant arctan x y π 2 når (x, y) ligger i 2. og 4. kvadrant 9
10 Løsningsforslag: Funksjonene φ 1 og φ 2 er begge kontinuerlige når x, y 0. Spesielt er de kontinuerlige i hver kvadrant, og siden de har de samme partielle deriverte, så skiller de seg fra hverandre med en konstant i hver kvadrant. Men som vi skal se, konstanten er forskjellig fra kvadrant til kvadrant: I likningen φ 1 (x, y) = φ 2 (x, y)+c setter vi inn punktet (1,1) fra første kvadrant, og får arctan(1) = arctan(1)+c, som gir C = π 2. Setter vi inn punktet ( 1, 1) fra tredje kvadrant får vi samme verdi for C. Setter vi så inn punktet ( 1,1) fra andre kvadrant får vi at arctan( 1) = arctan( 1) + C, som gir C = π 2. Setter vi inn punktet (1, 1) fra fjerde kvadrant får vi samme verdi for C. Setter vi inn for φ 1 og φ 2 får vi dermed at arctan y x arctan y x = arctan x y + π 2 = arctan x y π 2 i første og tredje kvadrant, eller når x y > 0, i andre og fjerde kvadrant, eller når x y < 0. f. Finn en potensialfunksjon φ for F i området A = {(x, y) R 2 y ligger ikke på den negative y-aksen} Forklar hvorfor du ikke kan utvide denne funksjonen φ til en kontinuerlig funksjon på hele R 2. Svar: For eksempel φ(x, y) = arctan( y x ) når x > 0 arctan( y x ) + π når x < 0 π 2 når x = 0 og y > 0 Denne funksjonen har et sprang langs den negative y-aksen. Løsningsforslag: Vi vet at φ 1 (x, y) = arctan y x +C er en potensialfunksjon for x 0, uansett verdi av C. For y > 0 har vi at lim φ 1(x, y) = π x C lim x 0 φ 1(x, y) = π 2 +C. Velger vi derfor potensialfunksjonen ψ 1 (x, y) = arctan y x + C for x > 0 og potensialfunksjonen ψ 2 (x, y) = arctan y x +C +π for x < 0 får vi at, for y > 0 lim ψ 1(x, y) = π x C lim x 0 ψ 2(x, y) = π 2 +C + π = π 2 +C, 10
11 slik at vi har en potensialfunksjon for F, ψ, definert ved ψ(x, y) = arctan y +C for x > 0, x ψ(x, y) = π +C for x = 0, y > 0, 2 ψ(x, y) = arctan y +C + π for x < 0, x som er kontinuerlig utenom den negative y-aksen. Gitt en verdi for C, så er det klart at dette er den eneste måten å kontinuerlig utvide φ 1 til planet utenom den negative y-aksen. For å se at det er umulig å utvide φ 1 til den negative y-aksen, regner vi ut, for y < 0, lim ψ(x, y) = lim arctan y x 0 + x 0 + x +C = π 2 +C lim ψ(x, y) = lim arctan y x 0 x 0 x +C + π = π 2 +C + π = 3π 2 +C. Derfor blir ikke utvidelsen vi har gjort kontinuerlig også på den negative y-aksen, slik at det er umulig å lage en kontinuerlig utvidelse til hele R Skisser grafen til funksjonen og sammenlign resultatet med det du får når du bruker Matlab. a. f (x, y) = 2x 2 + y 2 Løsningsforslag: Vi setter f (x, y) = 2x 2 + y 2. For nivåkurvene og konturkurvene har vi 2x 2 + y 2 = c gir en ellipse med store halvakse c, lille halvakse c 2. For c < 0 inneholder ikke nivåkurvene noen punkter, og for c = 0 består nivåkurven kun av origo. Skjæring med xz-planet er kurven z = 2x 2, og skjæring med yz-planet er kurven z = y 2. Alle andre konturkurver er også parabler, som er forskyvede versjoner av disse. % Oppgave a) r=-2:0.05:2; s=-2:0.05:2; [x,y]=meshgrid(r,s); z=2*x.^2+y.^2; mesh(x,y,z); title( Oppgave 3.7.2a ) 11
12 b. f (x, y) = y 2 x Løsningsforslag: y 2 x = c gir en nivåkurve som er en ligge parabel med åpning mot høyre. Toppunktet blir i (c,0). Dette gjør det lett å tegne eller se for oss flaten, siden alle parablene er forsyvede varianter av hverandre. Konturkurvene for flater parallelle med xz-planet ser vi at blir linjer (sett inn y like en konstant verdi i z = y 2 x), mens konturkurver for flater parallelle med y z-planet ser vi at blir parabler (sett inn x lik en konstant verdi i z = y 2 x). % Oppgave b) z=y.^2-x; figure(2) mesh(x,y,z); title( Oppgave 3.7.2b ) c. f (x, y) = sin(x 2 + y 2 ) Løsningsforslag: Vi setter f (x, y) = sin(x 2 + y 2 ). Nivåkurvene finner vi først ved å løse sin(x 2 + y 2 ) = c. Det er klart at denne har løsninger bare for 1 c 1, slik det ikke finnes nivåkurver utenfor dette intervallet. Videre er det mange løsninger for x 2 + y 2 for slike c: Først får vi at x 2 + y 2 = arcsinc er en løsning, men da er også x 2 + y 2 = arcsinc + 2kπ løsninger. Dette gir sirkler med radius arcsinc + 2kπ for k 0 eller k 1, avhengig av om c > 0 eller c < 0. Videre er x 2 + y 2 = π arcsinc + 2kπ også løsninger, siden sin(π x) = sin x for alle x. Dette gir sirkler med radius π arcsinc + 2kπ. Det er klart at disse radiusverdiene kommer tettere og tettere ettersom radiene vokser. Hver nivåkurve består altså av mange sirkler. For c = 1 eller c = 1 faller halvpartene av disse sirklene sammen, siden vinklene arcsinc og π arcsinc da faller sammen (arcsin(1) = π 2, arcsin( 1) = π 2 ). Det er kanskje lettest å tegne grafen ved å skrive den som z = sinr 2 i polarkoordinater. Flaten er altså et omdreiningslegeme som fremgår ved å dreie y = sin x 2, vist i Figur 1 om y-aksen. Figuren som fremkommer er vist i Figur 2. Konturkurver forteller kanskje ikke så mye her. % Oppgave c) r=-4:0.1:4; s=-4:0.1:4; 12
13 Figur 1: Grafen y = sin x 2 Figur 2: Grafen z = sin(x 2 + y 2 ) [x,y]=meshgrid(r,s); z=sin(x.^2+y.^2); figure(3) mesh(x,y,z); title( Oppgave 3.7.2c ) d. f (x, y) = x 2 4y 2 % Oppgave d) r=-5:0.05:5; s=-5:0.05:5; 13
14 [x,y]=meshgrid(r,s); z=x.^2-4*y.^2; figure(4); mesh(x,y,z); title( Oppgave 3.7.2d ); e. f (x, y) = ln(x y) Løsningsforslag: Hvis du forsøker å plotte ln(x y) i et intervall rundt null vil MATLAB rapportere problemer her, siden ln kun er definert for positive verdier. Funksjonen er derfor bare definert i første og tredje kvadrant. Det er kanskje enklest å tegne grafen ved hjelp av to plott, et for første kvadrant og et for tredje kvadrant, siden vi kan enkelt lage et grid for hver kvadrant: % Oppgave e) r=0.1:0.05:5; s=0.1:0.05:5; [x,y]=meshgrid(r,s); z=log(x.*y); mesh(x,y,z); hold on r=-5:0.05:-0.1; s=-5:0.05:-0.1; [x,y]=meshgrid(r,s); z=log(x.*y); mesh(x,y,z); title( Oppgave 3.7.2e ); 23. Skriv om funksjonen til polarkoordinater. Skisser grafen og sammenlign resultatet med det du får når du bruker Matlab. a. f (x, y) = 1 x 2 +y 2 Løsningsforslag: f (x, y) = 1 x 2 + y 2 = 1 r. % Oppgave a) u=-0.5:0.03:0.5; v=-0.5:0.03:0.5; [x,y]=meshgrid(u,v); 14
15 z=1./sqrt(x.^2 + y.^2); mesh(x,y,z); title( Oppgave 3.7.3a ) b. f (x, y) = x x 2 +y 2 Løsningsforslag: Vi kan skrive f (x, y) = x x 2 + y 2 = r cosθ r 2 = 1 r cosθ. Holder vi θ konstant, ser vi at vi får hyperbelen z = cosθ r. Dette hjelper oss til å kunne tegne opp flaten. Nivåkurvene er her sirkler: Setter vi c = får vi at x 2 + y 2 = x x 2 +y 2 c. Det er her greit at vi fullfører kvadratet i x for å se at vi får sirkler som er nivåkurver. % Oppgave b) u=-0.5:0.03:0.5; v=-0.5:0.03:0.5; [x,y]=meshgrid(u,v); z=x./(x.^2 + y.^2) figure(2) mesh(x,y,z) title( Oppgave 3.7.3b ) x c. f (x, y) = y x % Oppgave c) u=-0.5:0.03:0.5; v=-0.5:0.03:0.5; [x,y]=meshgrid(u,v); z=y./x; figure(3) mesh(x,y,z) title( Oppgave 3.7.3c ) d. f (x, y) = x 2 4y 2 Løsningsforslag: f (x, y) = x 2 4y 2 = r 2 cos 2 θ 4r 2 sin 2 θ = r 2 (cos 2 θ 4sin 2 θ) = r 2 (1 5sin 2 θ) = r 2 ( cos2θ). 15
16 Holder vi θ konstant, ser vi at vi får parabelen z = r 2 ( cos2θ). Nivåkurvene er her hyperbler. % Oppgave d) u=-1:0.05:1; v=-1:0.05:1; [x,y]=meshgrid(u,v); figure(4) z=x.^2-4*y.^2 mesh(x,y,z) title( Oppgave 3.7.3d ) e. f (x, y) = e x y % Oppgave e) u=-1:0.05:1; v=-1:0.05:1; [x,y]=meshgrid(u,v); figure(5) z=exp(x.*y); mesh(x,y,z); title( Oppgave 3.7.3e ) 24. I eksempel 3 i seksjon 2.2 studerte vi funksjonen f (x, y) = { x 2 y x 4 +y 2 for (x, y) (0,0) 0 når (x, y) = 0 som et eksempel på en funksjon som oppfører seg kontinuerlig når vi nærmer oss origo langs rette linjer, men ikke når vi følger parabelen y = x 2. Bruk Matlab til å tegne grafen til funksjonen, og studer fenomenet ved å dreie på grafen. Tegn også inn kurven r(t) = t i+t 2 j+ 1 2 k i samme figur. Tegn til slutt konturkurvene til funksjonen. % Oppgave r=-2:0.02:2; s=-2:0.02:2; [x,y]=meshgrid(r,s); 16
17 z=x.^2.*y./(x.^4+y.^2); figure(6) mesh(x,y,z) hold on t=linspace(0,2,100); plot3(t,t.^2,0.5*ones(1,length(t))) title( Oppgave ) hold off figure(7) contour(x,y,z); title( Oppgave ) contour(x,y,z,[ ]); title( Oppgave ) 25. I oppgave studerte vi funksjonen f (x, y) = { x 3 y x y 3 (x 2 +y 2 ) 2 for (x, y) (0,0) 0 når (x, y) = 0 som et eksempel på en funksjon der de blandede annenordens partiellderiverte er forskjellige. Bruk Matlab til å tegne grafen og konturkurvene til funksjonen, og prøv å forstå fra figuren hvorfor 2 f y x (0,0) er negativ mens 2 f x y (0,0) er positiv. Løsningsforslag: For å forklare hvordan vi kan forstå fra figuren hvorfor 2 f y x (0,0) er negativ og 2 f x y (0,0) er positiv, skriv først de partielle deriverte som grenseverdiene 2 f y x 2 f x y f f x (0,h) x (0,0) = lim (0,0) 1 f = lim h 0 h h 0 h x (0,h) (0,0) = lim h 0 f f y (h,0) y (0,0) h 1 f = lim h 0 h y (h,0), der vi har brukt at f f x (0,0) = y (0,0) = 0, som ble vist i Oppgave Fra funksjonsoppskriften er det klart at f skifter fortegn på koordinataksene, og på linjene y = x og y = x. Fortegnskjema for f er vist i Figur 3. La oss først se på f x (0,h) for små, positive verdier av h. Det er klart ved å studere flaten og fortegnskjemaet at f (x,h) går fra å være positiv til negativ ved x = 0, og vi har illustrert dette ved plott av f (x,0.1) i Figur??a). Dermed blir f f x (0,h) 0, slik at lim h h x (0,h) 0. At vi faktisk her har ekte ulikhet er ikke så lett å se fra grafen. For små, negative verdier av h er det på samme måte klart 17
18 Figur 3: Fortegnskjema for f (a) Plott av f (x, 0.1) (b) Plott av f (x, 0.1) Figur 4: Plott av f (x,h) for positiv og negativ h at f (x,h) går fra å være negativ til positiv ved x = 0, som illustrert ved plott av f (x, 0.1) i Figur??b). Dermed blir f x (0,h) 0, slik at lim h 0 1 f h x (0,h) 0. 1 f derfor må vi ha at lim h 0 h x (0,h) 0, slik at 2 f y x (0,0) 0. La oss deretter se på f y (h,0) for små, positive verdier av h. f (h, y) ser vi nå går fra å være negativ til positiv ved y = 0, slik at f y (h,0) 0, slik at lim h 0 1 f + h y (h,0) 0. For små, negative verdier av h er det på samme måte klart at f (h, y) går fra å være positiv til negativ ved y = 0, slik at f y (h,0) 0, slik at lim h 0 1 f h y (h,0) 0. 1 f derfor må vi ha at lim h 0 h y (h,0) 0, slik at 2 f x y (0,0) 0. % Oppgave r=-5:0.01:5; 18
19 s=-5:0.01:5; [x,y]=meshgrid(r,s); z=((x.^3).*y-x.*(y.^3))./(x.^2 + y.^2); mesh(x,y,z); title( Oppgave ) figure(2) contour(x,y,z); title( Oppgave ) 26. Tegn grafene til disse funksjonene med Matlab: f (x, y) = x 2 y 2, g (x, y) = sin x + x 2, h(x, y) = sin(e x+y ). Vri på flatene for å få et best mulig inntrykk. y 2 % Oppgave 5.1 r=linspace(-2,2,100); s=linspace(-2,2,100); [x,y]=meshgrid(r,s); f=(x.^2).* (y.^2); g=sin(x)./(y.^2)+x.^2; h=sin(exp(x+y)); mesh(x,y,f); figure(2) mesh(x,y,g); figure(3) mesh(x,y,h); 27. Bruk kommandoen quiver til å tegne vektorfeltet. Tegn også inn noen strømningslinjer. % Oppgave a) r=linspace(0,2*pi,30); s=linspace(0,2*pi,30); [x,y]=meshgrid(r,s); u=cos(x); v=sin(x); figure(8) quiver(x,y,u,v); title( Oppgave 3.8.1a ); 19
20 figure(9) streamline(x,y,u,v,0,1); hold on streamline(x,y,u,v,0,0.5); title( Oppgave 3.8.1a ); hold off % Oppgave b) r=linspace(-0.3,0.3,30); s=linspace(-0.3,0.3,30); [x,y]=meshgrid(r,s); u=-x./(x.^2+y.^2).^(3/2); v=-y./(x.^2+y.^2).^(3/2); figure(10) quiver(x,y,u,v) title( Oppgave 3.8.1b ); figure(11) streamline(x,y,u,v,-0.3,0.3); hold on streamline(x,y,u,v,0.3,0.3); title( Oppgave 3.8.1b ); hold off % Oppgave c) r=linspace(-2,2,30); s=linspace(-1,1,30); [x,y]=meshgrid(r,s); u=(1-x)./((x-1).^2+y.^2) + (1+x)./((x+1).^2+y.^2); v=-y./((x-1).^2+y.^2) + y./((x+1).^2 + y.^2); figure(12) quiver(x,y,u,v) title( Oppgave 3.8.1c ); figure(13) streamline(x,y,u,v,1.5,1); hold on streamline(x,y,u,v,0.5,1); title( Oppgave 3.8.1c ); hold off a. F(x, y) = cos x i + sin x j 20
21 b. F(x, y) = ( c. F(x, y) = x (x 2 +y 2 ) 3 2 i y (x 2 +y 2 ) 3 2 ) 1 x + 1+x (x 1) 2 +y 2 (x+1) 2 +y 2 j ( i + y (x 1) 2 +y I denne oppgaven skal vi se nærmere på vektorfeltet i eksempel 3 i seksjon 3.5 % Oppgave ac) r=-5:0.5:5; s=-5:0.5:5; [x,y]=meshgrid(r,s); u=-y./(x.^2 + y.^2); v=x./(x.^2 + y.^2); quiver(x,y,u,v); title( Oppgave 3.8.2ac ) hold on streamline(x,y,u,v,1,0); F(x, y) = y x 2 + y 2 i + x x 2 + y 2 j ) y j (x+1) 2 +y 2 a. Bruk kommandoen quiver til å tegne vektorfeltet. Bruk en forholdsvis grov oppdeling på aksene. b. Forklar at strømningslinjene til F er sirkler med sentrum i origo. c. Tegn strømningslinjen som starter i punktet (1, 0) på samme figur som vektorfeltet i a). Sammenlign resultatet med b). d. Gjenta punkt a) og c) med mye finere oppdeling av aksene. Hva skjer med strømningslinjene? 29. I denne oppgaven skal vi bruke Matlab til å eksperimentere litt med avbildninger slik som demonstrert i figur 5. Vi har altså en funksjon (u, v) = F(x, y) og vil se hvordan den avbilder et rutenett i x y-planet. For å slippe å lage et for omfatte program, skal vi nøye oss med en tilnærming der vi tegner opp hjørnene i det fordreide rutenettet og forbinder dem med rette streker (som i de fleste eksemplene burde vært buede kurver). Her er programmet i det tilfellet u = 3x y og v = x + 2y: 21
22 r=-2:0.25:2; %lager oppdeling av x-aksen s=-2:0.25:2; %lager oppdeling av y-aksen [x,y]=meshgrid(r,s); %lager rutenett av opppdelingene u=3.*x-y; %regner ut u av alle hjørnene i rutenettet v=x+2.*y; %regner ut v av alle hjørnene i rutenettet plot(u,v,u,v ) %tegner opp bildet av alle hjørnene i %rutenettet og forbinder dem med rette streker %Den første delen av kommandoen (dvs. plot(u,v)) %tegner opp strekene mellom "loddrette naboer", mens den %andre delen (dvs. plot(u,v )) tegner opp strekene mellom %"vannrette naboer". % Oppgave a) r=-2:0.25:2; %lager oppdeling av x-aksen s=-2:0.25:2; %lager oppdeling av y-aksen [x,y]=meshgrid(r,s); u=3.*x-y; v=x+2.*y; figure(14) plot(u,v,u,v ) title( Oppgave 3.8.3a ); % Oppgave b) r=0:0.25:5; s=0:0.25:(2*pi); [x,y]=meshgrid(r,s); u = x.*cos(y); v = x.*sin(y); figure(15) plot(u,v,u,v ); title( Oppgave 3.8.3b ); % Oppgave c) u=sqrt(x./y); v=sqrt(x.*y); figure(16) plot(u,v,u,v ); title( Oppgave 3.8.3c ); 22
23 a. Kjør programmet ovenfor med de angitte funksjonene u = 3x y og ( ) 3x y v = x + 2y. Beskriv rutenettet du ser (avbildningen F(x, y) = er x + 2y lineær). b. Kjør programmet på nytt, men la u = x cos y, v = x sin y, og bruk en oppdeling slik at 0 x 5, 0 y 2π. Beskriv rutenettet, og forklar sammenhengen med polarkoordinater. c. Kjør programmet igjen med u = x y og v = x y. Velg en oppdeling slik at x 0 og y 0. Beskriv rutenettet. 30. Bruk Matlab til å lage en tegning av den delen av kulen x 2 + y 2 + z 2 = 4 som ligger i første oktant (dvs. området der x, y, z 0. % Oppgave u=linspace(0,pi*0.5,100); v=linspace(0,pi*0.5,100); [U,V]=meshgrid(u,v); x=2*sin(v).*cos(u); y=2*sin(v).*sin(u); z=2*cos(v); surf(x,y,z) axis( equal ) title( Oppgave ) 31. Bruk Matlab til å lage en tegning av flaten i oppgave 7. % Oppgave u=linspace(0,2,100); v=linspace(0,2*pi,100); [U,V]=meshgrid(u,v); x=u; y=2*cos(v); z=2*sin(v); surf(x,y,z) axis( equal ) title( Oppgave ) 23
24 32. Bruk Matlab til å lage en tegning av flaten parametrisert ved r(u, v) = uv 2 i + u j + sin(uv)k, der 1 u 1,0 v 3 % Oppgave r=-1:0.05:1; s=0:0.05:3; [u,v]=meshgrid(r,s); figure(17) mesh(u.*v.^2,u,sin(u.*v)) title( Oppgave ); 33. Bruk Matlab til å lage en tegning av sylinderen x 2 + y 2 = 9, når 0 z 2. % Oppgave u=linspace(0,2*pi,100); v=linspace(0,2,100); [U,V]=meshgrid(u,v); x=3*cos(u); y=3*sin(u); z=v; surf(x,y,z) axis( equal ) title( Oppgave ) 34. Bruk Matlab til å lage en tegning av ellipsoiden i oppgave 6. Bruk samme målestokk på alle akser. a=1; b=0.5; c=0.1; u=linspace(0,2*pi,100); v=linspace(0,pi,100); [U,V]=meshgrid(u,v); x=sin(v).*cos(u)*a; y=sin(v).*sin(u)*b; 24
25 z=cos(v)*c; surf(x,y,z) axis( equal ) title( Oppgave ) 35. Bruk Matlab til å lage en tegning av en torus der r = 3 og R = 5. r=3; R=5; u=linspace(0,2*pi,100); v=linspace(0,2*pi,100); [theta,phi]=meshgrid(u,v); x=(5+3*cos(phi))*cos(theta); y=(5+3*cos(phi))*sin(theta); z=3*sin(phi); surf(x,y,z) title( Oppgave ) 36. Bruk Matlab til å omforme disse matrisene til redusert trappeform: % Oppgave a) rref([ ; ; ; ; ]) % Oppgave b) rref([ ; ; ]) % Oppgave c) rref([ ; ; ; ]) a. A = b. B =
26 c. C = Avgjør om ligningssystemet har en entydig løsning for alle valg av b 1,b 2,b 3. Bruk gjerne Matlab som hjelpemiddel. 2x y + z = b 1 x + 3y + 2z = b 2 3x 4y z = b 3 Svar: Nei % Oppgave rref([2-1 1;-1 3 2;3-4 -1]) 38. Finn alle løsningene til ligningssystemet. Bruk først Matlab til å skrive den utvidede matrisen på redusert trappeform. 2x y + z + 3u = 4 x + 2y + 4z + 3u = 2 2x + y + 3z 4u = 1 Svar: u kan velges fritt, men da må man sette x = u, y = u, z = u 4. Løsningsforslag: Den reduserte trappeformen kan dere få fra Matlab ved å skrive rref([ ; ; ]) Vi får da Dette betyr at u kan velges fritt (siden fjerde søyle ikke har noe pivotelement). Ved å flytte u-variablene over til høyre side får vi x = 3.5u y = 3.75u z = 0.25u
27 En vanlig måte å skrive dette på er x 3.5 y z = u u der de tre første radene stammer fra løsningene vi fant over, mens den siste bare uttrykker at u = u. % Oppgave rref([ ; ; ]) 39. Finn alle løsningene til ligningssystemet. Bruk først Matlab til å skrive den utvidede matrisen på redusert trappeform. x + y z + 2u v = 1 2x 2y + z u + v = 2 3x + 3y 2u + 2v = 1, Svar: v og y kan velges fritt, de andre variablene er da gitt ved: x = 7 y 2v, z = 26 7v, u = 10 2v. % Oppgave rref([ ; ; ]) 40. Skriv matrisen A = på redusert trappeform ved å la Matlab utføre radoperasjonene én for én (du får altså ikke lov til å bruke rref eller en ligne kommando). Beskriv den generelle løsningen til ligningssystemet som har A som utvidet matrise. % Oppgave A=[ ; ; ]; A([1 2 3],:)=A([2 1 3],:); k=a(3,1)/a(1,1); 27
28 A(3,:)=A(3,:)-k*A(1,:); A(1,:)=A(1,:)/A(1,1); k=a(3,2)/a(2,2); A(3,:)=A(3,:)-k*A(2,:); A(2,:)=A(2,:)/A(2,2); k=a(2,3)/a(3,3); A(2,:)=A(2,:)-k*A(3,:); k=a(1,3)/a(3,3); A(1,:)=A(1,:)-k*A(3,:); A(3,:)=A(3,:)/A(3,3); A 41. a. Figuren viser spillebrettet for et enkelt terningspill. Spillerne starter på Start og kaster en vanlig terning for å flytte. De trenger eksakt riktig antall øyne for å gå i mål (står de på 11 og kaster en femmer, spretter de altså ut til 10 ved å telle på denne måten 12-mål ). La t i være antall kast du må regne med å gjøre før du går i mål (dvs. det forventede antall kast) dersom du står på felt i. Mål Start Forklar hvorfor 28
29 t 1 = 1 6 t t t t t t t 2 = 1 6 t t t t t t t 6 = 1 6 t t t t t t t 7 = 1 6 t t t t t t 8 = 1 6 t t t t t 9 = 1 6 t t t t 10 = 1 6 t t t t 11 = 1 6 t t t t t 12 = 1 6 t t t t t Forklar videre hvorfor dette er et lineært ligningssystem og bruk Matlab til å løse dette. Hvor mange kast må du regne med å bruke når du står på start? b. Løs problemet i a) når du ikke trenger eksakt antall øyne for å komme i mål. % Uppgift 7.5 t=-1/6; T=[1,t,t,t,t,t,t,0,0,0,0,0,1;... 0,1,t,t,t,t,t,t,0,0,0,0,1;... 0,0,1,t,t,t,t,t,t,0,0,0,1;... 0,0,0,1,t,t,t,t,t,t,0,0,1;... 0,0,0,0,1,t,t,t,t,t,t,0,1;... 0,0,0,0,0,1,t,t,t,t,t,t,1;... 0,0,0,0,0,0,1,t,t,t,t,t,1;... 29
30 0,0,0,0,0,0,0,1,t,t,t,2*t,1;... 0,0,0,0,0,0,0,0,1,t,2*t,2*t,1;... 0,0,0,0,0,0,0,0,1,t,2*t,2*t,1;... 0,0,0,0,0,0,0,1,t,t,t,2*t,1;... 0,0,0,0,0,0,1,t,t,t,t,t,1]; rref(t) 42. Bruk Matlab til å finne den inverse matrisen dersom den finnes: % Oppgave a) inv([ ; ; ; ]) % Oppgave b) inv([ ; ; ; ]) % Oppgave c) inv([ ; ; ; ; ]) a. A =
31 b. B = c. C = Bruk Matlab-kommandoen >> x=a\b til å løse matriseligningen Ax = b når: Løsningsforslag: % Oppgave a) [2-1 3; 0-1 2; ]\[-1; 2; 3] % Oppgave b) [ ; ; ; ]\[4; -3; 0; 1] a. A = b. A = , b = , b = 44. Bruk Matlab-kommandoen >> x=b/a til å løse matriseligningen xa = b når: Løsningsforslag: % Oppgave a) [-1 2 3]/[2-1 3; 0-1 2; ] % Oppgave b) [ ]/[ ; ; ; ] a. A = , b = ( 1,2,3) 31
32 b. A = oppgave Skriv som en lineærkombinasjon av, b = (4, 3,0,1) Sammenlign med svarene på , Bruk gjerne Matlab som hjelpemiddel. Svar: Koeffisientene er x 1 = 100 9, x 2 = 17 9, x 3 = 11 27, x 4 = % Oppgave rref([ ; ; ; ]) 46. Bruk Matlab til å skrive , , , som en lineærkombinasjon av Svar: Koeffisientene er: x 1 = , x 2 = , x 3 = , x 4 = , % Oppgave rref([ ; ; ; ]) 47. Bruk Matlab til å sjekke om enhver vektor i R 4 kan skrives som en lineærkombinasjon av , 3 4, 7 10, 3 1, Svar: Ja % Oppgave rref([ ; ; ; ]) ,. 32
33 48. Vi skal i denne oppgaven modifisere koden vår fra seksjon?? for å bringe en matrise på redusert trappeform, slik at vi får litt mer informasjon. Løsningsforslag: Som du kanskje husker så kan en funksjon i Matlab ha vilkårlig mange ut-parametre. Vi kan derfor lage en funksjon som løser både a), b), og c) samtidig, ved at vi lager en ut-parameter for hver av disse deloppgavene. Siden vi i Oppgave blir bedt om å lage a en variant av samme funksjon, så har vi også tatt med a en ut-parameter, slik at koden under også løser Oppgave : % De fire ekstra ut-verdiene løser a), b), c) og , respektive. % colslinind forteller om søyler er lineært uavhengige (løser a)) % kons forteller om systemet er konsistent (løser b)) % infmany forteller om systemet har uelig mange løsninger (løser c)) % rang gir rangen til matrisen (løser ) function [U,colslinind,kons,infmany,rang]=040613(A) [m,n]=size(a) % leser antall rader søyler i A kons=true; infmany=false; i=1; % i er en radindeks. Vi starter i første rad for j=1:n % Gjennomgå en og en søyle, med j som søyleindeks [maksverdi,p] = max(abs(a(i:m,j))); q = p+i-1; A([i q],:) = A([q i],:); % Bytt om rad i og q if A(i,j)~=0 for r=i+1:m A(r,:) = A(r,:) -(A(r,j)/A(i,j))*A(i,:); i=i+1; if j==n kons=false; elseif j<n infmany=true; if i>m break U=A; colslinind=(i>m); 33
34 rang=i-1; a. Legg merke til i koden at hvis vi for en søyle ikke øker radindeks i med 1, så blir ikke denne søylen en pivotsøyle, og setning?? sier at søylene må være lineært avhengige. Bruk denne observasjonen til å re koden slik at den sier om søylene i matrisen er lineært uavhengige. b. Anta nå at matrisen representerer en utvidet matrise. Hvis radindeksen økes med 1 for siste søyle, så er det klart at denne er en pivotsøyle, slik at systemet er inkonsistent. Bruk denne observasjonen til å re koden slik at den sier om systemet er konsistent eller ikke. c. Hvis radindeksen ikke økes med 1 for en av søylene før den siste, så er det klart at systemet har uelig mange løsninger hvis det er konsistent, siden da er ikke en av søylene før den siste en pivotsøyle. Bruk denne observasjon til å re koden slik at den sier om systemet har en eller uelig mange løsninger hvis det er konsistent. 49. Bruk Matlab til å finne rangen til matrisene A = , B = Svar: Koden blir % Oppgave a) rank([ ; ; ]) % Oppgave b) rank([ ; ; ; ]) 50. Bruk Matlab til å finne en ortonormal basis for rommet H utspent av a 1 = 1 2 1, a 2 = 2 2 0, a 3 = Svar: Koden blir 34
35 % Oppgave orth([1 2-1;-2 2 3;1 0 2]) 51. I oppgave modifiserte du koden fra seksjon?? (som brakte en matrise på trappeform) slik at den samtidig ga mer informasjon om matrisen. Modifiser den slik at den også returnerer rangen til matrisen. Løsningsforslag: Vi har her utvidet funksjonen du laget i Oppgave slik at den også returnerer rangen til matrisen. 52. Bruk Matlab til å regne ut determinanten til matrisen: % Oppgave a) det([ ; ; ; ; ]) % Oppgave b) det([ ; ; ; ; ]) a. b. b) Vi har i flere oppgaver tidligere modifisert koden fra seksjon?? som brakte en matrise på trappeform, slik at den samtidig ga mer informasjon om matrisen. Løsningsforslag: Her kunne vi brukt koden fra Oppgave og , men i stedet velger vi å skrive ny kode. Forskjellen her er at det holder å bringe matrisen på trappeform, og at vi ikke trenger å holde styr på både radindeks og søyleindeks: Hvis vi øker søyleindeksen uten å øke radindeksen så må jo determinanten bli 0, siden vi blir ståe igjen med en 0 på diagonalen. 35
36 function determ=o040912(a) [m,n]=size(a) % leser antall rader og søyler i A determ=1; for j=1:n % Gjennomgå en og en søyle, med j som søyleindeks [maksverdi,p] = max(abs(a(j:m,j))); q = p+j-1; A([j q],:) = A([q j],:); % Bytt om rad j og q if A(j,j)~=0 for r=i+1:m A(r,:) = A(r,:) -(A(r,j)/A(j,j))*A(j,:); determ=determ*a(j,j); else determ=0; break; a. Modifiser koden fra seksjon?? slik at den også returnerer determinanten til matrisen. Hint: bruk Teorem?? til å regne ut determinanten, gitt at du allerede har funnet trappeformen til matrisen. b. Vis at antall addisjoner og multiplikasjoner koden din gjør for en n nmatrise, gitt at vi ikke trenger å bytte om noen rader under radreduksjon, er gitt ved P(n), der P er et tredjegradspolynom. Finn polynomene som gjelder for antall multiplikasjoner og addisjoner. c. Bruk kommandoene tic og toc til å sammenligne tiden koden din bruker, sammenlignet med det funksjonen detdef bruker (vi implementerte denne i slutten av denne seksjonen). Velg selv matrisestørrelsene, slik at funksjonene ikke bruker for lang tid. Er resultatene rimelige, når vi sammenligner antall addisjoner og multiplikasjoner de to funksjonene bruker? 54. Bruk Matlab til å finne egenverdien og egenvektorene til matrisen A. Bruk også Matlab til å skrive vektoren x som en lineærkombinasjon av egenvektorene: % Oppgave a) A=[1-2 4; 0 5 4; ]; 36
37 [V,D]=eig(A) rref([v [0.3; 2.4; -3.4]]) % Oppgave b) A=[ ; ; ; ]; [V,D]=eig(A) rref([v [-1.3; 2.4; 0.04; 4.1]]) a. A = b. A = ,x = ,x = Oppgave c) ga ganske mye regning for å finne egenverdiene og egenvektorene (kvadratrøtter inngikk i uttrykkene). Verifiser at du regnet riktig i denne oppgaven ved å bruke Symbolic math Toolbox i Matlab. 56. Bruk kommandoene rand(2,2), rand(3,3), rand(4,4) og rand(5,5) til å generere tilfeldige matriser. Finn egenverdiene og egenvektorene i hvert enkelt tilfelle. Hvor mange forskjellige egenverdier ser det ut til at en typisk n n- matrise har? % Oppgave 6.4 a=rand(2,2); [V,D]=eig(a) a=rand(3,3); [V,D]=eig(a) a=rand(4,4); [V,D]=eig(a) a=rand(5,5); [V,D]=eig(a) 57. To fiskeslag lever i samme innsjø. Fiskeslag II er avhengig av fiskeslag I for å opprettholde bestanden. Dersom x(t) er antall fisk av slag I ved tiden t, og y(t) er antall fisk av slag II ved tiden t, regner vi at x (t) = 0.02x(t) 0.03y(t) 37
38 y (t) = 0.01x(t) 0.02y(t) % Oppgave d) t=linspace(0,1000,1000); x=6000*exp(0.01*t) *exp(-0.01*t); y=2000*exp(0.01*t) *exp(-0.01*t); plot(t,x) hold on plot(t,y) title( Oppgave d ) ( a. Vis at egenverdiene og egenvektorene til matrisen A = er λ 1 = 0.01,λ 2 = 0.01,v 1 = ( x(t) b. La r(t) = y(t) ) og skriv r(t) = c 1 (t)v 1 +c 2 (t)v 2. Vis at c 1 og c 2 tilfredsstiller differensialligningene ( 3 1 ),v 2 = ( 1 1 ). c 1 (t) = 0.01c 1(t) ) c 2 (t) = 0.01c 2(t) c. Anta at x(0) = 5000 og y(0) = Finn x(t) og y(t). Hvordan går det med forholdet x(t) y(t) mellom antall fisk av slag I og antall fisk av slag II når t blir stor? Svar: x(t) = 6000e 0.01t 1000e 0.01t, y(t) = 2000e 0.01t 1000e 0.01t d. Bruk Matlab til å plotte x(t) og y(t) i samme koordinatsystem. 58. En by har nettopp innført et system med bysykler der man kan låne en sykkel fra et sykkelstativ og levere den fra seg ved et annet (eller ved det samme om man bare skal en tur i nærområdet). Foreløpig har byen 4 stativer som vi kaller X, Y, Z, U. Myndighetene er interessert i å undersøke lånemønsteret for syklene, 38
39 Utgangspunkt Prosentfordeling neste måned i X i Y i Z i U ute av drift X 40% 20% 20% 10% 10% Y 10% 40% 20% 20% 10% Z 10% 20% 25% 25% 20% U 30% 20% 20% 20% 10% og har derfor en månedlig undersøkelse av hvor de forskjellige syklene befinner seg. Denne undersøkelsen viser at av de syklene som befant seg i stativ X en måned, befinner 40% seg i X måneden etter, 20% befinner seg i Y, 20% i Z og 10% i U, mens 10% er ute av drift fordi de enten er forsvunnet eller inne til vedlikehold. Tilsvare tall for syklene som opprinnelig var i Y, Z og U, fremgår av tabellen ovenfor. I forbindelse med undersøkelsen får hvert stativ påfyll med nye/reparerte sykler. Påfyllet tilsvarer 15% av antall sykler som står i stativet. Svar: En utvidet versjon av denne oppgaven ligger på med løsningsforslag på a. La x n, y n, z n, u n være antall sykler i henholdsvis X, Y, Z, U rett etter den n-te undersøkelsen (og rett etter påfyllet av nye/reparerte sykler). Forklar at x n+1 = 0.46x n y n z n u n y n+1 = 0.23x n y n z n u n z n+1 = 0.23x n y n z n u n u n+1 = 0.115x n y n z n u n Løsningsforslag: Antall sykler i stativ X rett før påfyllingen i måned n + 1 er lik 40% av antall sykler i X måneden før, pluss 10% av antall sykler i Y måneden før, pluss 10% av antall sykler i Z måneden før, pluss 30% av antall sykler i U måneden før, dvs. 0.4x n +0.1y n +0.1z n +0.3u n. Ganger vi dette med 1.15 for å fange opp påfyllet, får vi x n+1 = 0.46x n y n z n u n. De andre likningene fremkommer på tilsvare måte. b. Skriv en m-fil som gitt x 1, y 1, z 1, u 1 returnerer x n, y n, z n, u n for n fra 1 til 50. Løsningsforslag: Vi kaller funksjone vi skal lage for bysykler. Denne kan programmeres slik: 39
40 function C=bysykler(a,b,c,d) % Hver kolonne i C svarer til et tidspunkt. % 1. rad inneholder alle x-verdier, andre rad alle y-verdier osv. C=[a;b;c;d]; A=[ ; ; ; ]; for n=1:49 C(:,n+1) = A*C(:,n); Vi bruker deretter denne funksjonen i resten av oppgaven: % Oppgave c) C=bysykler(100,100,100,100); plot(c(1,:)); hold on plot(c(2,:), r ) plot(c(3,:), g ) plot(c(4,:), y ) % Oppgave d) powers = ^[0:49]; D(1,:)=C(1,:)./powers; D(2,:)=C(2,:)./powers; D(3,:)=C(3,:)./powers; D(4,:)=C(4,:)./powers; plot(d(1,:)); hold on plot(d(2,:), r ) plot(d(3,:), g ) plot(d(4,:), y ) % Oppgave e) C=bysykler(200,0,0,200); % Kjør c) og d) som før ellers c. Velg x 1 = y 1 = z 1 = u 1 = 100, og bruk Matlab til å tegne følgene {x n }, {y n }, {z n }, {u n } i samme koordinatsystem. d. Lag en ny figur der du plotter følgene { }, { }, { }, { n n n 1 i samme koordinatsystem. x n y n z n u n } n 1 e. Gjenta plottingen i c) og d), men bruk starttilstanden x 1 = 200, y 1 = 0, z 1 = 0, u 1 = 200. Ser du et mønster? Eksperimenter gjerne med andre startverdier. 40
41 f. La w n = x n y n z n u n være fordelingen av sykler den n-te måneden. Forklar at w n+1 = Aw n der A er matrisen A = Forklar også hvorfor w n = A n 1 w 1. Løsningsforslag: Det er klart at hver rad i matrisen A svarer til koeffisientene i en av likningene vi fant i a). Men da er det klart at w n+1 = Aw n når vi setter w n = x n y n z n w n. % Oppgave g) A=[ ; ; ; ]; [U,V]=eig(A) U(1,:)=-U(1,:); % Gjør at egenvektoren for egenverdien % med størst absoluttverdi får positive tall. % Oppgave h) rref(u) % Oppgave i) rref([u [100;100;100;100]]) g. Bruk Matlab til å vise at matrisen A ovenfor har fire egenverdier λ 1, λ 2, λ 3, λ 4 med tilhøre egenvektorer v 1, v 2, v 3, v 4. Sørg for å ordne rekkefølgen slik at λ 1 er egenverdien med størst tallverdi. (NB: MATLAB gir av og til egenvektorer der alle komponentene er negative. For å få en egenvektor som er greiere å arbeide med, kan du da bare fjerne alle minustegnene i denne vektoren.) h. Vis at egenvektorene v 1, v 2, v 3, v 4 til A danner en basis for R 4, dvs. at de er lineært uavhengige og utspenner hele R 4 (bruk gjerne MATLAB). 41
42 i. Velg w 1 = og skriv denne vektoren som en lineærkombinasjon av v 1, v 2, v 3, v 4 (bruk gjerne MATLAB). Finn A n 1 w 1 lim n λ n 1 1 Sammenlign med resultatene i oppgave 1c) og d). Hva regner du med å få dersom du velger en annen starttilstand w 1? 59. En følge {x n, y n } i R 2 er gitt ved x 1 = y 1 = 0 og x n+1 = 0.6x n 0.6y n y n+1 = 0.6x n + 0.6y n + 1 Skriv et program som beregner elementer i følgen, og tegn dem inn i en figur. Vis at funksjonen ( ) 0.6x 0.6y + 0,2 F(x, y) = 0.6x + 0.6y + 1 har et fikspunkt. Svar: Fikspunkt ( 1, 1). % Oppgave N = 500; x=zeros(2,n); x(:,1)=[0;0]; for n=1:n x(:,n+1)=[ ; ]*x(:,n) + [0.2;1]; plot(x(1,:),x(2,:)) 60. To dyreslag lever i det samme området. Dersom det er hhv. x n og y n dyr av hvert slag i området ett år, regner man at tallene året etter er gitt ved x n+1 = 0.9x n y n 10 y n+1 = 1.01x n + y n
43 Skriv et program som beregner hvordan bestanden utvikler seg, og plott resultatet når x 1 = 20, y 1 = Finn et likevektspunkt for bestandene. Svar: Likevektspunkt: x 297, y 3970 Løsningsforslag: Et likevektspunkt for bestandene kan vi finne ved å sette x n = x n+1 = x og y n = y n+1 = y i likningene fra oppgaven. Vi får da Samler vi variablene får vi Dette systemet kan vi løse ved å skrive [ ; ]\[-10; 300] x = 0.9x y 10 y = 1.01x + y x 0.01y = x = 300 som gir verdiene x 297, y I plottet du får skal du se vi starter iterasjonene i (20, 2000), og at verdiene deretter går i spiral inn mot dette likevektspunktet. Koden blir % Oppgave antalliterasjoner=200; x=zeros(2,antalliterasjoner+1); x(:,1)=[20;2000]; for n=1:antalliterasjoner x(:,n+1)=[ ; ]*x(:,n)+[-10; 300]; plot(x(1,:),x(2,:)) 61. I denne oppgaven skal vi se på befolkningsutviklingen i to land. Dersom innbyggertallet (målt i millioner) i de to landene er hhv. x n og y n ett tiår, regner man at de tilsvare tallene ti år etter er gitt ved x n+1 = 1.1x n y n 0.5 y n+1 = 0.95y n x n Skriv et program som beregner hvordan innbyggertallene utvikler seg, og plott resultatet når x 1 = 50, y 1 = 8. 43
44 % Oppgave N = 100; x=zeros(2,n); x(:,1)=[50;8]; for n=1:n x(:,n+1)=[ ; ]*x(:,n) + [-0.5; 0.2]; plot(x(1,:)) hold on plot(x(2,:), r ) 62. To bensinstasjoner X og Y konkurrerer ved å tilpasse seg hverandres priser. Dersom prisene en uke er hhv. x n og y n, vil stasjon X uken etter sette sin pris til 1.01 xn+y n 2, mens stasjon Y vil velge den prisen som er lavest av x n og 1.1y n. Lag et program som viser hvordan prisene vil utvikle seg. Kjør programmet både med x 1 = 8, y 1 = 12 og med x 1 = 12, y 1 = 8. Sammenlign prisutviklingene. % Oppgave antalliterasjoner=200; x=zeros(antalliterasjoner+1); y=zeros(antalliterasjoner+1); x(1)=8; % 12 y(1)=12; % 8 for n=1:antalliterasjoner x(n+1)=1.01*(x(n)+y(n))/2; y(n+1)=min(x(n),1.1*y(n)); plot(x,y) figure(2) x(1)=12; y(1)=8; for n=1:antalliterasjoner x(n+1)=1.01*(x(n)+y(n))/2; y(n+1)=min(x(n),1.1*y(n)); 44
45 plot(x,y) 63. To insektstyper konkurrerer om det samme området. Anta at x n og y n er antall insekter (målt i millioner) i området i år n. Vi regner at bestanden i år n +1 da er gitt ved x n+1 = 2.2x n (1 x n ) x n y n y n+1 = 3.1y n (1 y v ) 0.02x n y n Skriv et program som beregner hvordan bestandene utvikler seg, og plott resultatet når x 1 = 0.5, y 1 = 0.5 og når x 1 = 0.1, y 1 = 0.8. Eksperimenter også med andre startverdier i intervallet (0,1). % Oppgave antalliterasjoner=200; x=zeros(antalliterasjoner+1); y=zeros(antalliterasjoner+1); x(1)=0.5; % 0.1 y(1)=0.5; % 0.8 for n=1:antalliterasjoner x(n+1)=2.2*x(n)*(1-x(n)) *x(n)*y(n); y(n+1)=3.1*y(n)*(1-y(n)) *x(n)*y(n); plot(x,y) I de fleste andre oppgavene avhenger x n+1, y n+1 lineært av x n, y n, og vi kan da finne generelle uttrykk for x n, y n ved å finne egenvektorene til koeffisientmatrisen slik vi har gjort mange ganger. I denne oppgaven avhenger ikke x n+1, y n+1 lineært av x n, y n, slik at denne strategien ikke leder frem til generelle uttrykk for x n, y n. Selv om vi ikke klarer finne et slikt generelt uttrykk, så kan vi likevel finne et uttrykk for likevektspunktet: setter vi x n = x n+1 = x og y n = y n+1 = y i likningene fra oppgaven får vi x = 2.2x(1 x) x y y = 3.1y(1 y) 0.02x y Forkorter vi med x i den første likningen og med y i den andre likningen, får vi 1 = 2.2(1 x) y 1 = 3.1(1 y) 0.02x. 45
46 Samler vi leddene får vi 2.2x 0.01y = x + 3.1y = 2.1, som gir (0.5485, ) som likevektspunkt (vi har også tre andre likevektspunkter, et i origo, et når x = 0, y 0, et når x 0, y = 0). Hvis vi i koden for denne oppgaven bruker dette punktet som utgangspunkt, vil vi se at de første iterasjonene ligger nær punktet vi startet i (husk at avrundingsfeil inntrer slik at vi ikke vil fortsette i eksakt samme punkt), mens vi etter en stund vil bevege oss bort fra punktet. Systemet ser altså ut til å ha en frastøte effekt, som sørger for å skyve oss bort fra likevektspunktet. I plottene fra MATLAB virker det ellers som at iterasjonene hopper mellom to punkter, bare vi fortsetter langt nok. 64. To firmaer konkurrerer i det samme markedet. Dersom prisene på produktet deres (målt i tusen kroner) er hhv. p og q, regner firmaene med å selge hhv. E 1 (p, q) = 1000e p q α(p+q) og E 2 (p, q) = 1000e q p β(p+q) eksemplarer, der α og β er konstanter. % Oppgave b) N = 50; a=0.02; b=0.03; x=zeros(2,n); x(:,1)=[10;12]; for n=1:n x(1,n+1)=1.1*(x(2,n)/(1+a*x(2,n))); x(2,n+1)=1.1*(x(1,n)/(1+b*x(1,n))); plot(x(1,:)) hold on plot(x(2,:), r ) 46
47 a. Anta at prisen q ligger fast. Vis at firma 1 da får størst salgsinntekter ved å selge sitt produkt for p =. Vis tilsvare at hvis p ligger fast, q 1+αq så får firma 2 størst salgsinntekter ved å selge sitt produkt for q = p 1+βp. b. Det første året velger firmaene prisene p 1 og q 1. De bestemmer seg for at prisen året etter skal være hhv. p 2 = 1.1p1 = 1.1 q 1 1+αq 1 og q 2 = 1.1q1 = 1.1 p 1 1+βp 1. Denne politikken holder de fast ved i årene som kommer. Skriv et program som beregner prisutviklingen for de to produktene. Parametrene α og β skal inngå blant input-variablene. c. Kjør programmet med α = β = Bruk startverdiene (x 1, y 1 ) = (3,4), (x 1, y 1 ) = (4,3), (x 1, y 1 ) = (1,1.3), (x 1, y 1 ) = (1.3,1) og sammenlign resultatene. d. Gjenta punkt c) med α = 0.05, β = La f : R R være funksjonen f (x) = x 2 + x 2. Vis at x = 2 er et fikspunkt for f. Skriv et program som utfører iterasjonen x n+1 = f (x n ). Start programmet med x 1 = 2. Hva skjer (du bør nok utføre ca. 30 iterasjoner før du ser noe)? Forklar! % Oppgave antalliterasjoner=30; x=zeros(antalliterasjoner+1); x(1)=sqrt(2); x(1) for n=1:antalliterasjoner x(n+1)=x(n)^2+x(n)-2; x(n+1) 66. Skriv et program for iterasjon av funksjoner f : [0,π] R gitt ved f (x) = b sin x, der b er en konstant. Eksperimenter med forskjellige startverdier og forskjellige b-verdier slik vi gjorde med funksjonen f (x) = bx(1 x) i teksten. % Oppgave N=30; b=0.5; x=zeros(1,n); 47
48 x(1)=pi/2 for n=1:n x(n+1)=b*sin(x(n)) plot(x) 67. I denne oppgaven skal vi se på en grafisk metode for å studere iterasjon av en kontinuerlig funksjon f av én variabel. I figur 1 har vi tegnet opp funksjonsgrafen og linjen y = x i samme koordinatsystem. y = x y = f (x) Figur 1 a. Forklar at fikspunktene til f er det samme som skjæringspunktene mellom linjen y = x og grafen til f. y = x x 2 x 0 x 3 x 1 Figur 2 b. Figur 2 viser hvordan vi grafisk kan finne punktene x 1 = f (x 0 ), x 2 = f (x 1 ), x 3 = f (x 2 ) osv. Forklar hvordan og hvorfor metoden virker. c. Figur 3 viser en bane med periode 2. Lag en tilsvare figur som viser en bane med periode 3 (du kan godt bruke en annen funksjonsgraf y = f (x)). 48
49 y = x x 0 x 1 Figur 3 d. I resten av oppgaven skal vi se på funksjoner f : [0,1] [0,1] gitt ved f (x) = bx(1 x), der 0 b 4. Vis at dersom b > 1, så har f to fikspunkter 0 og 1 1 b. e. Velg b = 7 2. Vis at banen som starter i x 0 = 3 7 er periodisk med periode 2. f. Bruk Matlab eller en lommeregner til å tegne grafen til f 2. Vis at grafen skjærer linjen y = x i punktene 0, 3 7, 5 7 og 6 7. Forklar. g. (arbeidskreve) Vis at dersom 3 < b 4, så har funksjonen f (x) = bx(1 x) baner med periode to som starter i punktene b+1± (b 1) 2 4 2b. 68. I denne oppgaven skal vi se på iterasjon av funksjonen F : R 2 R 2 gitt ved ( 1 F(x, y) = 2 sin(x + y), 1 ) cos(x y) 2 function [x,y]=oppg01(x1,y1,antalliterasjoner) x=zeros(antalliterasjoner+1); y=zeros(antalliterasjoner+1); x(1)=x1; y(1)=y1; for n=1:antalliterasjoner x(n+1)=0.5*sin(x(n)+y(n)); y(n+1)=0.5*cos(x(n)-y(n)); 49
50 % Oppgave % b) [x,y]=oppg01(1,-1,30); plot(x,y) axis([ ]); % c) for k=1:6 x1=5*rand()-2.5; y1=5*rand()-2.5; [x,y]=oppg050501(x1,y1,30); subplot(2,3,k); plot(x,y) axis([ ]); a. Lag et program for å beregne følgen gitt ved u n+1 = F(u n ). b. Kjør programmet ditt med startpunkt u 1 = (x 1, y 1 ) = (1, 1) og et passe antall iterasjoner. Plott følgen {u n }. c. Kjør programmet 6 ganger til. I hvert tilfelle lar du programmet velge et tilfeldig startpunkt (x 1, y 1 ) med 2.5 x 1, y (kommandoen >> rand produserer et tilfeldig tall mellom 0 og 1). Tegn opp sekvensene i hvert sitt subplot, og sett aksene slik at resultatene er lette å sammenligne. 69. I denne oppgaven skal vi eksperimentere med en annen type fikspunkter. Disse fikspunktene er mengder som ikke forandrer seg når vi anver en sammensetning av funksjoner på dem. Vi starter med funksjonene T 1 : R 2 R 2, T 2 : R 2 R 2 og T 3 : R 2 R 2 gitt ved T 1 (x, y) = ( x 2, y 2 ), T2 (x, y) = ( x , y 2 ) og T3 (x, y) = ( x , y a. La S være den likesidede trekanten med hjørner i punktene (0,0), (1,0) og ( 1 2, 3 2 ). Beskriv bildene T 1(S), T 2 (S) og T 3 (S) av S under henholdsvis T 1, T 2 og T 3 (husk at generelt er T(S) = {T(x, y) (x, y) S}). b. La S 1 være det samlede bildet av S under T 1, T 2 og T 3 (vi har altså S 1 = T 1 (S) T 2 (S) T 3 (S)). Beskriv bildet S 2 av S 1 under T 1, T 2 og T 3 (vi har altså S 2 = T 1 (S 1 ) T 2 (S 1 ) T 3 (S 1 )). Lag en skisse av S 1 og S 2. Hvordan tror du S 3 og S 4 blir see ut? Hvordan går det når du tegner inn S n for 50 )
51 alle n? Mengden A vi da får kalles Sierpinski-trekanten, og den er et slags fikspunkt i den forstand at den ikke rer seg når vi bruker T 1, T 2 og T 3 på den (dvs. at A = T 1 (A) T 2 (A) T 3 (A)). Vi skal nå se på følge prosedyre: Start med et punkt (x 1, y 1 ) i planet. Velg tilfeldig én av funksjonen T 1,T 2,T 3, og la (x 2, y 2 ) være det punktet vi får når vi bruker denne funksjonen på (x 1, y 1 ). Velg på ny én av funksjonen T 1,T 2,T 3 på en tilfeldig måte, og la (x 3, y 3 ) være det punktet vi får når vi bruker denne funksjonen på (x 2, y 2 ). Fortsetter vi på denne måten, får vi en følge av punkter {(x n, y n )} i planet. Det viser seg at denne følgen alltid hoper seg opp på den samme mengden. Vi skal undersøke dette fenomenet nærmere. c. Forklar at følge program implementerer prosedyren ovenfor: function x=sierpinski(a,b,n) x(:,1)=[a;b]; for n=1:n z=rand; if z<=1/3 x(:,n+1)=x(:,n)/2; elseif z<=2/3 x(:,n+1)=x(:,n)/2+[1/2;0]; else x(:,n+1)=x(:,n)/2+[1/4;sqrt(3)/4]; plot(x(1,:),x(2,:),. ) Du må sannsynligvis bruke hjelpefunksjonen for å finne ut av noen av kommandoene. d. Legg programmet ovenfor på en m-fil og kjør det med forskjellige inputverdier a, b og N. Beskriv det du ser. Velg noen av kjøringene, og presenter dem i samme figur ved hjelp av kommandoen subplot. (Hint: Du bør velge N opp til størrelsesorden for å få et godt bilde, men det er lærerikt også å se på mindre verdier av N. Det kan også være lurt å bruke kommandoen axis( equal ) før du lagrer bildene.) e. Undersøk også hvordan programmet nedenfor fungerer (rett opp figurene med axis( equal ) ). 51
52 function x=blomst(r,d,s,n) x(:,1)=[1;0]; for n=1:n z=rand; if z<=0.95 x(:,n+1) = r*[cos(pi/d) -sin(pi/d); sin(pi/d) cos(pi/d)]*x(:,n); elseif z>.95 x(:,n+1) = s*x(:,n) + [1;0]; plot(x(1,:),x(2,:),. ) Kjør programmet først med r = 0.97,d = 7, s = 1 6, N = 10000, men eksperimenter også med andre verdier. Bruk de to funksjonene F 1 (x, y) = r (x cos π d y sin π d, x sin π d + y cos π d ) og F 2(x, y) = (sx + 1, sy) til å forklare hvordan bildene fremkommer. (Hint: I en typisk kjøring vil man velge F 1 mange ganger før F 2 dukker opp første gang. Deretter kommer sannsynligvis en ny sekvens av F 1 ere osv. Prøv å knytte dette bildet til de geometriske tolkningene av F 1 og F 2.) 70. La f : R R være funksjonen f (x) = x 3 x. a. Vis at f har tre nullpunkter. Svar: Nullpunkter: 0, ±1. Løsningsforslag: Vi kan skrive f (x) = x 3 x = x(x 2 1) = x(x 1)(x + 1), slik at f har de tre nullpunktene 0,1, 1. b. Skriv et program for å finne nullpunktene til f ved hjelp av Newtons metode. Løsningsforslag: Det er best å bruke en eksistere implementasjon av Newtons metode som har følge signatur: function x=newton(x0,f,df) der x0 er startpunktet for Newtons metode, og f, df er anonyme funksjoner som representerer f og den deriverte til f. Eksempel på en slik funksjon, som terminerer etter passe antall iterasjoner, finnes på bokas hjemmeside. Vi kan nå bruke funksjonen newton til å løse c) slik: % Oppgave c) 52
53 c. Kjør programmet ditt med startverdier 0.4, 0.5 og 0.6. Prøv å gjette hva som skjer før du kjører programmet. d. Prøv å forklare resultatene i c) geometrisk ved å studere hvordan Newtons metode virker. 71. Funksjonen F : R 2 R 2 er gitt ved ( F(x, y) = x 2 y x 2 + y 2 1 a. Skriv et program for å finne nullpunktene til F ved hjelp av Newtons metode. Løsningsforslag: Som i Oppgave er det best å bruke en eksistere implementasjon av Newtons metode i flere variable. Signaturen kan nå i stedet bli ) function x=newtonfler(x0,f,j) der x0 er startpunktet, og F, J er anonyme funksjoner som representerer F og dens Jacobimatrise F. Eksempel på en slik funksjon, som terminerer etter passe antall iterasjoner, finnes også på bokas hjemmeside. Vi kan nå bruke funksjonen newtonfler til å løse b) slik: % Oppgave ; 2*x(1) -1; 2*x(1) 2*x(2)]) b. F har to nullpunkter. Finn begge to ved å velge forskjellige startverdier. 5 1 Svar: (±0.7862, 0, 6180) c) (± 2, ) 53
54 c. Finn nullpunktene til F ved regning og sjekk at svarene stemmer med det du fant i b). Løsningsforslag: For at førstekomponenten skal bli 0 må y = x 2. Setter vi dette inn i andrekomponenten får vi at y 2 + y 1 = 0. Formelen for andregradslikningen gir da at y = 1± 1+4 2, eller y = 1± 5 2. Siden y = x 2 må y være positiv, slik at y = er eneste mulighet. Vi må ha at x = ± ( , slik at nullpunktene er (x, y) = ( , ). 72. Funksjonen F : R 2 R 2 er gitt ved F(x, y) = 1 2 sin(x + y) 1 2 cos(x y) , ) og (x, y) = % Oppgave *cos(x(1)+x(2)); *sin(x(1)-x(2)) 0.5*sin(x(1)-x(2))]) a. Beskriv de (uelig mange) nullpunktene til F. Svar: Førstekomponenten er null på alle linjer x + y = kπ, k Z, mens annenkomponenten er null på alle linjer x y = π 2 + mπ, m Z. Funksjonen er null i alle skjæringspunkter mellom slike linjer. b. Skriv et program for å finne nullpunktene til F ved hjelp av Newtons metode. c. Eksperimenter med forskjellige startverdier og se hvordan Newtons metode finner frem til forskjellige nullpunkter. 73. Funksjonen F : R 2 R 2 er gitt ved ( y 2 ) x 3 F(x, y) = x 2 y + sin(x y) 2 Skriv et program for å finne nullpunktene til F ved hjelp av Newtons metode. Bruk programmet til å finne i hvert fall to (tilnærmede) nullpunkter. 54
55 % Oppgave 2*x(2);2*x(1)+cos(x(1)-x(2)) -1-cos(x(1)-x(2))]) 74. Skriv et program for å løse ligningssystemet e x+y = sin(x y) y 2 x 2 = 1 Finn en (tilnærmet) løsning av systemet. % Oppgave exp(x(1)+x(2));-2*x(1) 2*x(2)]) 75. Skriv et program for å løse ligningssystemet x 2 + y 2 + z 2 = 9 x 2 y 2 + 2z 2 = 1 x + y + 10z = 1 Finn minst to (tilnærmede) løsninger av systemet. % Oppgave x(1)^2-x(2)^2 + 2*x(3)^2-1;... 2*x(2) 2*x(3); 2*x(1) -2*x(2) 4*x(3); ]) x(1)^2-x(2)^2 + 2*x(3)^2-1;... 2*x(2) 2*x(3); 2*x(1) -2*x(2) 4*x(3); ]) 55
56 76. I denne oppgaven skal vi se på konvergensraten i setning Skriv et program som regner ut noen ledd av følgen z n = (1 1 2h) 2n 2 n for h = 1 2, h = 0.4 og h = 0.3. Sammenlign konvergenshastighetene. % Oppgave N=10; h=0.5; z=zeros(1,n); for n=1:n z(n)=((1-sqrt(1-2*h))^(2^n))/(2^n); z(n) 77. I denne oppgaven skal vi se på et enkelt eksempel på hvordan Kantorovitsj teorem kan brukes i praksis. Eksemplet er så enkelt at det å bruke Kantorovitsj teorem er å skyte spurver med kanoner, men hensikten er å illustrere bruken av teoremet i en situasjon der de regnetekniske komplikasjonene forsvinner. Vi skal bruke Newtons metode til å finne et nullpunkt for funksjonen f (x) = x cos x (ifølge skjæringssetningen må det finnes et nullpunkt). Vi starter iterasjonen med x 0 = 0. % Oppgave newton(0,@(x)x-cos(x),@(x)1+sin(x)) a. Vis at f (x) 2 for alle x. Forklar at vi dermed kan velge M = 2 i Kantorovitsj teorem. b. Vis at f (x 0 ) = 1. Forklar at vi kan bruke K = 1 i Kantorovitsj teorem. c. Sjekk at f (x 0 ) 1 f (x 0 ) = 1, og forklar at betingelsen i Kantorovitsj teorem ikke er oppfylt for startpunktet x 0 = 0 og de verdiene vi har funnet for K og M. d. Bruk allikevel Newtons metode til å regne ut at x 1 = 1. 56
57 e. Vi skal nå bruke Kantorovitsj teorem med x 1 som utgangspunkt. Forklar at vi nå kan bruke M = 2, K = 0.6 og vis at x 2 x Konkluder med at Kantorovitsj teorem garanterer at iterasjonen konvergerer mot et nullpunkt for f. 78. Vi skal studere likningssystemet x 2 + y 2 48 = 0 x + y + 6 = 0 a. Lag et implisitt plott av de to likningene i samme figurvindu (du kan for eksempel lage et kontur-plott med en enkelt nivåkurve for funksjonsverdien 0). Bruk figuren til å bestemme hvor mange løsninger dette likningssystemet har. Løsningsforslag: Vi tegner opp nivåkurvene f (x, y) = 0 og g (x, y) = 0 i samme figurvindu (og skriver plottet til filen kontur.eps) med følge kode: r=-10:0.1:10; s=-10:0.1:10; [x,y]=meshgrid(r,s); f=x.^2+y.^2-48; g=x+y+6; contour(x,y,f,[0 0]) % tegner opp en nivaakurve hvor f=0 hold( on ) contour(x,y,g,[0 0]) % tegner opp en nivaakurve hvor g=0 axis( square ) hold( off ) print -deps kontur.eps Av figuren ser vi at de to nivåkurvene skjærer hverandre i to punkter, så likningssystemet har to løsninger. b. Bruk figuren du lagde i punkt a) til å finne fornuftige startverdier for Newtons metode, og kjør deretter funksjonen newtonfler med disse startverdiene og passe anonyme funksjoner for å finne tilnærmede verdier for nullpunktene. Løsningsforslag: Vi ser av figuren i punkt a) at de to nullpunktene ligger i nærheten av ( 7,1) og (1, 7), så det kan være lurt å prøve disse som startverdier. Vi utfører Newtons metode på vår vektorvaluerte funksjon og på dens Jacobimatrise med startpunkt ( 7,1), ved hjelp av koden 57
58 >> 2*x(2); 1 1]) x = Denne verdien er nær å være et nullpunkt, som utskriften fra for-løkken viser oss. NB! Husk på at startpunktet skal angis som en søylevektor. For å finne en tilnærmingsverdi til det andre nullpunktet, bruker vi startpunktet (1, 7) og skriver >> 2*x(2); 1 1]) x = Denne verdien er også nær å være et nullpunkt. 79. Vi skal studere likningssystemet Finn anonyme funksjoner f (x, y, z) = y 2 + z 2 3 = 0 g (x, y, z) = x 2 + z 2 2 = 0 h(x, y, z) = x 2 z = 0 F = [f; g; h] J = [dfx,dfy,dfz;dgx,dgy,dgz;dhx,dhy,dhz] som beskriver funksjonsverdiene og Jacobimatrisen til funksjonen F (x, y, z) medkomponenter f (x, y, z), g (x, y, z), h(x, y, z)). Bruk disse og funksjonen newtonfler til å finne en tilnærmet løsning på likningssystemet. Merknad: I kallet på fprintf som vi benyttet tidligere for å få en pen utskrift på skjermen av alle de beregnede tilnærmingsverdiene, ba vi bare om å få skrevet ut de to første komponentene til x og F(x). For å få en utskrift av alle de tre komponentene (med litt færre desimaler enn sist, slik at vi får plass å skjermen), kan du f.eks modifisere koden slik: 58
59 fprintf( itnr=%2d x=[%9.6f,%9.6f,%9.6f] F(x)=[%9.6f,%9.6f,%9.6f]nn,... n,x(1),x(2),x(3),f(1),f(2),f(3)) Ellers er det ingen ringer som trengs å gjøres i koden til newtonfler. Løsningsforslag: For å kjøre funksjonen newtonfler på dette likningssystemet med startpunkt x = (1, 7,5), skriver vi >> x(1)^2+x(3)^2-2; 2*x(2) 2*x(3); 2*x(1) 0 2*x(3); 2*x(1) 0-1]) x = Også her er verdien som regnes ut veldig nær å være et nullpunkt. 80. La f (x, y) = (x 2 y 2 )e x2 +y 2 2. a. Finn de stasjonære punktene til f og avgjør om de er lokale maksimumspunkter, lokale minimumspunkter eller sadelpunkter. Svar: (0,0) er et sadelpunkt, (± 2,0) er lokale (og globale) maksimumspunkter, (0,± 2) er lokale (og globale) minimumspunkter. Løsningsforslag: De partielle deriverte er f x = (2x x3 + x y 2 )e x 2 +y 2 2 f y = ( 2y x2 y + y 3 )e x 2 +y 2 2. De stasjonære punktene får vi ved å løse 2x x 3 + x y 2 = 0 2y x 2 y + y 3 = 0. Hvis x = 0 ser vi at eneste mulighet for y er at y = 0, y = 2, y = 2. Hvis y = 0 ser vi at eneste mulighet for x er at x = 0, x = 2, x = 2. Hvis både x og y er forskjellige fra 0 ser vi at som jo ikke har noen løsninger = x 2 y 2 2 = y 2 x 2,
60 Vi ser derfor at de eneste stasjonære punktene er (0,0),(0, 2),(0, 2),( 2,0),( 2,0). Vi regner så ut andreordens partielle deriverte: 2 f x 2 = (2 5x2 + y 2 + x 4 x 2 y 2 )e 2 f x y = (x3 y x y 3 )e x 2 +y 2 2 x 2 +y f y 2 = ( 2 x2 + 5y 2 + x 2 y 2 y 4 )e x 2 +y 2 2. Hesse-matrisene blir ( ) 2 0 H f (0,0) = 0 2 H f (0, ( 4e 1 ) 0 2) = 0 4e 1 H f (0, ( 4e 1 ) 0 2) = 0 4e 1 H f ( ( 4e 1 0 2,0) = 0 4e 1 H f ( ( 4e 1 0 2,0) = 0 4e 1 Alt her er diagonalmatriser, og da vet vi at egenverdiene står på diagonalen. Vi ser derfor at (0,0,0) er sadelpunkt, (0, 2, 2e 1 ),(0, 2, 2e 1 ) er minimumspunkter, ( 2,0,2e 1 ),( 2,0,2e 1 ) er maksimumspunkter. b. Finn maksimum og minimum til f på området {(x, y) x 1, y 3}. Bruk Matlab eller en lommeregner til å tegne grafen. Svar: Minimumsverdi: 2e 1 i (0,± 2). Maksimumsverdi: e 1 2 i (±1,0) Løsningsforslag: Legg først merke til at to av de stasjonære punktene ligger utenfor rektanglet vårt, slik at vi trenger bare ta med de to første kandidatene ovenfra videre. Vi må nå sjekke hvilke andre kandidater til maksimum og minimum vi får fra randen til området. Hvis x = 1 får vi funksjonen f (y) = (1 y 2 )e 1+y2 2. Av uttrykket for de partielle deriverte ser vi at denne er 0 når 2y y + y 3 = y 3 3y = 0, altså når y = 0, eller når y = ± 3 Dette gir oss nye kandidater 60 ) ).
61 (±1,0,e 1/2 ) (±1,± 3, 2e 2 ) (±1, 3, 2e 2 ) Hvis y = 3 får vi funksjonen f (x) = (x 2 9)e x Av uttrykket for de partielle deriverte ser vi at denne er 0 når 2x x 3 + 9x = 11x x 3 = 0, altså når x = 0, eller når x = ± 11. De siste punktene ligger utenfor rektanglet vårt, slik at det er bare (0,±3, 9e 9/2 ) som blir ny kandidat. Vi må også spesielt sjekke punktene der både x = 1, y = 3. Dette gir kandidatene (±1,±3, 8e 5 ) (±1, 3, 8e 5 ) Sammenligner vi verdiene til alle kandidatene ser vi at (±1,0,e 1/2 ) er globale maksimum, mens (0,± 2, 2e 1 ) er globale minimum. % Oppgave b) [x,y]=meshgrid(-3:0.01:3); z=(x.^2 - y.^2).*exp(-(x.^2 + y.^2)/2); mesh(x,y,z) 81. I denne oppgaven skal vi se på noen viktige forskjeller mellom funksjoner av henholdsvis én og flere variable. a. La f : R R være en deriverbar funksjon av én variabel og anta at det eneste stasjonære punktet til f er et lokalt maksimum i a. Vis at da er a et globalt maksimum for f. Løsningsforslag: Anta at a er det eneste stasjonære punktet til f, og at det er et lokalt maksimum. Anta for motsigelse at a ikke er et globalt maksimum. Da finnes det en b slik at f (b) > f (a). På intervallet [a,b] vet vi at f har et minimum, og vi vet også at dette minimum vil inntreffe i et indre punkt d, siden a er et lokalt maksimum og b et globalt maksimum. Men da vet vi at d er et stasjonært punkt for f, som strider mot at a er det eneste stasjonære punktet for f. Derfor må a være et globalt maksimum. 61
62 b. La f (x, y) = 1 x 2 (1 + x) 3 y 2 Vis at (0,0) er det eneste stasjonære punktet til f. Løsningsforslag: Vi får at f x = 2x 3(1 + x)2 y 2 f y = 2(1 + x)3 y Vi har to muligheter for at f y = 2(1 + x)3 y = 0, nemlig x = 1 og y = 0. x = 1 innsatt i f x = 0 gir 2 = 0, som ikke har noen løsning. x = 0 innsatt gir at y = 0 er eneste løsning, slik at (0,0) er det eneste stasjonære punktet. c. Vis at (0,0) er et lokalt maksimum, men ikke et globalt maksimum for f. Bruk Matlab til å tegne grafen til f, og tenk gjennom forskjellen på én og flere dimensjoner. Løsningsforslag: Vi regner ut 2 f 2 = 2 6(1 + x)y x2 2 f x y = 6(1 + x)2 y 2 f = 2(1 + x)3 y 2 Setter vi inn x = 0, y = 0 får vi 2 f (0,0) = 2 x2 2 f x y (0,0) = 0 2 f (0,0) = 2 y 2 ( ) 2 0 slik at H f (0,0) =. Her er det klart at begge egenverdiene er 0 2 negative, slik at (0,0) må være et maksimumspunkt. For å se at (0,0) ikke er et globalt maksimum kan vi regne ut f ( 2, y) = y 2 = 3 + y 2. Det er klart at dette går mot når y, slik at (0,0) umulig kan være et globalt maksimum. For å forklare forskjellen mellom en og to variable, legg først merke til at en funksjon i en variabel må ha derivert lik null i et punkt en går fra å være vokse til stige (og omvt). Dette gjelder også for de partielle deriverte til en funksjon i to variable, men det er ikke sikkert at de partielle deriverte er null samtidig, som kreves for at vi skal ha et stasjonært punkt. Derfor kan det være flaten ikke har andre stasjonære punkt, men at verdiene likevel snur og går mot. 62
63 % Oppgave c) u=linspace(-3,3,100); v=linspace(-3,3,100); [x,y]=meshgrid(u,v); f=1 - x.^2 - ((1+x).^3).*(y.^3); mesh(x,y,f) d. La g : R R være en kontinuerlig funksjon av én variabel og anta at a og b er to lokale maksimumspunkter for f. Vis at det finnes et lokalt minimumspunkt mellom a og b. Løsningsforslag: g restriktert til [a, b] vet vi at har et lokalt minimum. Det er klart at dette punktet er forskjellig fra a og b, siden verdiene av g i nærheten av disse er mindre enn eller lik g (a) og g (b). e. La g (x, y) = 4x 2 e y 2x 4 e 4y Vis at de stasjonære punktene til g er ( 1,0) og (1,0). Løsningsforslag: Vi har at g x = 8xe y 8x 3 g y = 4x2 e y 4e 4y Setter vi dette lik 0 ser vi at x = 0 løser den første likningen, men er ikke forenlig med det andre likningen. Deler vi med 8x i den første likningn får vi e y = x 2. Dette innsatt i den andre likningen gir 4x 4 4x 8 = 0, som gir x 4 = 1. Det er klart at x = ±1 er de eneste løsningene her, og det følger også at y = 0. Dermed er (1,0) og ( 1,0) de eneste stasjonære punktene til g. f. Vis at begge de to stasjonære punktene til g er lokale maksimumspunkter. Bruk Matlab til å tegne grafen til g, og tenk gjennom forskjellen på én og flere dimensjoner. Løsningsforslag: Vi regner ut 2 g x 2 = 8e y 24x 2 2 g x y = 8xe y 2 g y 2 = 4x2 e y 16e 4y Setter vi inn x = ±1, y = 0 får vi 2 g (0,0) = 16 x2 2 g (0,0) = ±8 x y 2 g (0,0) = 12 y 2 63
64 ( 16 ±8 slik at H f (±1,0) = ±8 12 ). Determinanten blir her > 0, og siden A = 16 < 0 er det klart at begge punktene er maksimum. % Oppgave f) u=linspace(-3,3,100); v=linspace(-3,3,100); [x,y]=meshgrid(u,v); g=4*(x.^2).*exp(y) - 2*x.^4 - exp(4*y); mesh(x,y,g) 82. Skriv et program som bruker gradientmetoden til å finne minimumspunktet til f (x, y) = x 2 +2x y +2y 2 +x y. Sjekk resultatet ved å finne minimumspunktet ved regning. 83. Bruk Matlab til å regne ut integralene i oppgave 1. % Oppgave % a) % Integraler kan regnes ut på flere måter i Matlab. % De fire eksemplene nedenfor returnerer alle samme svar % Ved hjelp av anonym funksjon dblquad( x.*y,1,2,2,4) % Samme som over, men enklere syntaks. f=inline( x.*y ); dblquad(f,1,2,2,4) % Ved hjelp av linjefunksjon % Symbolsk kan vi regne ut integralet slik syms x y uttrykk1=int( x*y, x,1,2) uttrykk2=int(uttrykk1, y,2,4) eval(uttrykk2) % b) dblquad(@(x,y)x+sin(y),0,1,0,pi) % c) dblquad(@(x,y)x.^2.*exp(y),-1,1,0,1) % d) dblquad(@(x,y)x.*cos(x.*y),1,2,pi,2*pi) 64
65 % e) % f) % g) 84. Bruk Matlab til å regne ut integralene i oppgave 1. % Oppgave a) dblquad(@(x,y)(x.^2).*y.*(y<=x),0,2,0,2) % Symbolsk utregning: syms x y uttrykk1=int( x^2*y, y,0,x); uttrykk2=int(uttrykk1, x,0,2); eval(uttrykk2) % Oppgave b) dblquad(@(x,y)(x+2*x.*y).*(x<=y).*(y<=(2*x+1)),0,3,0,7) % Oppgave c) dblquad(@(x,y)y.*(y<=x).*(x<=y.^2),1,4,1,2) % Oppgave d) dblquad(@(x,y)(x.*cos(y)).*(x<=sin(y)),0,1,0,pi/2) % Oppgave e) dblquad(@(x,y)exp(x.^2).*(y<=x),0,1,0,1) % Oppgave f) dblquad(@(x,y)(x.^2).*y.*(y<=sqrt(x)).*(x.^2<=y),0,1,0,1) % Oppgave g) dblquad(@(x,y)x.*cos(x+y).*(y<=x),0,pi,0,pi) % Oppgave h) 65
66 pi^2/8 % Oppgave i) dblquad(@(x,y)x.*(((x-1)./(exp(1)-1))<=y).*(y<=log(x)),1,exp(1),0,1) 85. Bruk Matlab til å regne ut integralene i oppgave 1. % Oppgave a) dblquad(@(r,theta)(r.^4).*cos(theta).*(sin(theta).^2),0,3,0,pi/2) % Oppgave b) dblquad(@(r,theta)(r.^3),0,5,0,pi/4) % Oppgave c) dblquad(@(r,theta)r.*exp(r.^2),1,4,0,2*pi) % Oppgave d) dblquad(@(r,theta)r.^3.*sin(theta).*cos(theta),0,1,0,pi/4) % Oppgave e) dblquad(@(x,y)(x.^2-y.^2).*(x.^2+y.^2<=1)....*(y >= sqrt(3).*x).*(y <= sqrt(3).*x./3),-1,0,-1,0) % Oppgave f) dblquad(@(r,theta)r.*sqrt(2-(r.*cos(theta)).^2-(r.*sin(theta)).^2)...,0,1,0,pi/2) % Oppgave g) dblquad(@(x,y)(x.^2+y.^2).^(3/2).* ((x-1).^2 +y.^2 <= 1),0,2,-1,1) 86. Kurven C er gitt ved r(t) = t sin(t)i + (2πt t 2 )j, t [0,2π] Skisser kurven (f.eks. ved å bruke Matlab) og regn ut arealet til området den avgrenser. Svar: 4π 2 66
67 Løsningsforslag: Skisserer vi kurven ser vi at orienteringen er mot klokka, slik at vi kan bruke Greens teorem direkte. Vi setter P(x, y) = 0 og Q(x, y) = x i Greens teorem og får A = = 2π = 2π xd y = C 2π 0 2π 0 t sin t 2 [ t cos t + t sin t(2π 2t)dt 2π 0 cos tdt t 2 sin tdt ] 2π 0 [ 2 t 2 cos t + ] 2π 2t cos tdt 0 = 2π[ t cos t + sin t] 2π 0 2[ t 2 cos t + 2t sin t + 2cos t ] 2π 0 = 4π 2 2( 4π 2 + 2) + 4 = 4π 2 % Oppgave t=linspace(0,2*pi,100); x=t.*sin(t); y=2*pi*t-t.^2; plot(x,y) 87. Kurven C er gitt ved r(t) = sin2t i + t cos t j, t [0, π 2 ] Skisser kurven (f.eks. ved å bruke Matlab) og regn ut arealet til området avgrenset av kurven. 10 3π Svar: 9 Løsningsforslag: I dette tilfellet vil vi kunne skjønne hva orienteringen må bli ved å regne ut fartsvektoren i startpunktet 0 og i sluttpunktet π 2. Vi får først at v(t) = r (t) = (2cos(2t),cos t t sin t), og deretter v(0) = (2,1) og v( π 2 ) = ( 2, π 2 ). Tegner vi opp disse to vektorene som startretning og sluttretning er det klart at orienteringen må bli positiv. Vi kan derfor bruke Greens teorem direkte. Setter vi 67
68 etter vi P(x, y) = 0, Q(x, y) = x får vi derfor A = = = C π/2 0 xd y = π/2 0 sin(2t)(cos t t sin t)dt (2sin t cos 2 t 2t sin 2 cos t)dt [ 2 3 cos3 t ] π/2 = [ t 3 sin3 t 0 [ t sin3 t 3 sin3 tdt 1 3 (1 cos2 t)sin tdt = [ t 3 sin3 t 1 3 ( cos t cos3 t) ] π/2 0 ] π/2 0 ] π/2 = 2 3 2(π ) = π 3 = 10 9 π 3 % Oppgave t=linspace(0,pi/2,100); plot( sin(2*t), t.*cos(t) ); axis equal; π = Bruk Matlab til å regne ut integralene i oppgave 1 uten å skifte variabel. % Oppgave a) dblquad(@(x,y)x.^2.*(x<=y).*(y<=x+1).*(-x<=y).*(y<=-x+2),-0.5,1,0,1.5) % Oppgave b) dblquad(@(x,y)x.*(y<=x).*(x-3<=y),0,4,0,1) % Oppgave c) dblquad(@(x,y)x.*y.*(y<=2*x).*(y<=(x/2)+2).*(2*x-2<=y).*(x/2<=y),... 0,8/3,0,10/3) 89. Bruk Matlab til å regne ut integralene i oppgave 3 uten å skifte variabel. % Oppgave a) dblquad(@(x,y)x.*y.*(x+2*y>=-1).*(x+2*y<=3).*(x-y>=1).*(x-y<=4),... 1/3,11/3,-5/3,2/3) 68
69 % Oppgave b) - y.^2).*exp(x+y).*(-x<=y).*(x<=y).*(y<=x+2)....*(y<=-x+2),-1,1,0,2) % Oppgave c) dblquad(@(x,y)(y.^2 - y.*x).*(x<=y).*((1./x)<=y).*(y<=2*x).*(y<=(2./x)),... (1/sqrt(2)),sqrt(2),1,2) 90. Bruk Matlab til å regne ut integralene i oppgave 5 uten å skifte variabel. % Oppgave a) dblquad(@(x,y)(x<=y).*(y<=x+5).*(-x+2<=y).*(y<=-x+4).*exp(x-y)./(x+y)...,-1.5,2,1,4.5) % Oppgave b) dblquad(@(x,y)x.*y.*(x<=y).*((1./x)<=y).*(y<=2*x).*(y<=(3./x)),0,2,0,5) % Oppgave c) dblquad(@(x,y)y.*((x./2)<=y).*((1./x.^2)<=y).*(y<=2*x)....*(y<=(2./x.^2)),(2^(-1/3)),(4^(1/3)),((2^(1/3))/2),2) % Oppgave d) dblquad(@(x,y)(3*x-2*y).*(x/2<=y).*((3*x-5)<=y)....*(y<=3*x).*(y<=((x/2)+ 5/2)),0,3,0,4) % Oppgave e) dblquad(@(x,y)x.*((x-1).^2<=y).*(x.^2<=y).*(y<=x.^2+4)....*(y<=(x-1).^2+4),-3/2,5/2,0,17/4) 91. Bruk Matlab til å regne ut integralene i oppgave 1 (det kan ta tid!). % Oppgave a) triplequad(@(x,y,z)(x.*y.*z),0,1,0,1,0,1) % Oppgave b) triplequad(@(x,y,z)(x+y.*exp(z)),-1,1,0,1,1,2) 69
70 % Oppgave c) % Oppgave d) % Oppgave e) 92. Bruk Matlab til å regne ut integralene i oppgave 2 (det kan ta tid!). % Oppgave a) triplequad(@(x,y,z)(x.*y + z).*(z<=((x.^2).*y)),0,1,0,2,0,2) % Oppgave b) triplequad(@(x,y,z)z.*(y<=sqrt(x)).*(-(y.^2)<=z).*(z<=(x.*y)),... 0,2,0,sqrt(2),0,2*sqrt(2)) % Oppgave c) triplequad(@(x,y,z)(x+y).*z.*(x<=sqrt(y)),0,2,0,4,0,4) % Oppgave d) triplequad(@(x,y,z)(3*y.^2-3*z).*(3*x+2*y-6<=z).*(y<=(-3.0/2.0)*x+3),... 0,2,0,3,0,-6) % Oppgave e) triplequad(@(x,y,z)(x.*y).*(z<=-x-y+1).*(y<=-x+1),0,1,0,1,0,1) 93. På slutten av seksjon 6.1 forklarte vi hvordan dobbeltintegralet kan regnes ut symbolsk ved hjelp av Matlab. De samme kallene kan brukes til å regne ut trippelintegraler symbolsk i Matlab. Regn ut trippelintegralet (x + ye 2z )dzd ydx, ved å bruke tilsvare kall som i slutten av seksjon
71 94. Ligningene ( X (u, v) = 1 + v 2 cos u ) cosu ( 2 Y (u, v) = 1 + v 2 cos u ) sinu 2 Z (u, v) = v 2 sin u 2 der 0 u 2π, 1 v 1 gir en parametrisering av et Möbiusbånd. Bruk Matlab til å lage en tegning av båndet. 95. Flaten T har parameterfremstillingen r(u, v) = uv cos v i + uv sin v j + uv k, u [0,1], v [0,2π] og kurven C er gitt ved s(t) = t cos t i + t sin t j + t k, t [0,2π] a. Finn arealet til T og buelengden til C. Lag en tegning av flaten (bruk gjerne Matlab). Svar: Areal: 4 2π 3 3, buelengde: π 4π log(2π + 4π 2 + 2) log 2 b. La F(x, y, z) = yz i + xz j. Finn T curlf nds både ved direkte utregning og ved hjelp av Stokes teorem. Bruk enhetsnormal n med positiv tredjekomponent. Svar: 4π I denne oppgaven er T flaten z = x 2 y 2 og F er vektorfeltet F(x, y, z) = yz i xz j + z k. a. Tegn nivåkurvene til T for z lik 4, 1,0,1,4, og lag en skisse av flaten. Bruk gjerne Matlab. b. Finn divergensen og curlen til F. Svar: divf = 1,curlF = x i + y j + 2z k c. La C være skjæringskurven mellom T og sylinderflaten x 2 + y 2 = 4, og orienter C slik at den har positiv omløpsretning sett ovenfra. Bruk Stokes teorem til å beregne C F dr. Svar: 0 71
72 d. Parametriser C og beregn linjeintegralet ovenfor uten å bruke Stokes teorem. Svar: Parametriseringen kan f.eks. være r(t) = 2cos t i+2sin t j+4(cos 2 t sin 2 t)k e. La V være området i første og fjerde kvadrant som ligger under flaten T, over x y-planet og innenfor sylinderen x 2 + y 2 = 4. Finn volumet til V. Svar: 4 f. La T 0 være den delen av overflaten til V som er del av T. Finn T 0 F nds der n har positiv z-komponent. Svar: Bruk Matlab til å regne ut: , 5/7, 3 2, % Oppgave /7 3^2 (2.3-4^2)/(13-2.2^2) La Matlab regne ut verdiene, og sjekk at resultatene er rimelige: e 1, 16, cosπ, sin π 6, tan π 4, arcsin 1 2, arctan1. % Oppgave 1.2 exp(1) sqrt(16) cos(pi) sin(pi/6) tan(pi/4) asin(1/2) atan(1) 99. Definer x = og y = e 1 og regn ut: x + y, x y, x y og sin x2 y % Oppgave 1.3 x=0.762 y=sqrt(9.56)+exp(-1) x+y 72
73 x*y x/y sin(x^2)*y 100. Legg inn disse n-tuplene i Matlab: (1, 9,7,5, 7), (π, 14,e,7/3), (1,3,5,7,9,...,99), (124,120,116,112...,4,0). % Oppgave 3.1 a=[ ]; b=[pi -14 exp(1) 7/3]; c=1:2:99 d=124:(-4): Legg inn tuppelet (1,2,4,8,16, ) i Matlab og finn summen. % Oppgave 3.2 e=2.^(0:12) sum(e) 1 100, Legg inn (0, 100,...,1) i Matlab. Bruk denne partisjonen til å lage en nedre og øvre trappesum for funksjonen f (x) = x 2 over intervallet [0,1] (husk MAT 1100!), og regn ut disse summene. Sammenlign med integralet 1 0 x2 dx. % Oppgave 3.3 a=0:1:100; a=a./100; b=sum(a.^2); (1/100)*(b-1) % Nedre trappesum (1/100)*b % Øvre trappesum 103. Bruk Matlab til å regne ut produktet % Oppgave 3.4 a=1:2:100; b=2:2:100; c=a./b; prod(c)
74 104. Legg inn 6-tuplene a = (3,1, 2,5,4,3) og b = (4,1, 1,5,3,1) i Matlab og utfør kommandoen» plot(a,b). Utfør også kommandoene» plot(a) og» plot(b), og bruk» hold on til å sørge for at de to siste figurene kommer i samme vindu. % Oppgave 4.1 a=[ ]; b=[ ]; plot(a,b) plot(a) hold on plot(b) 105. Bruk kommandoen» plot til å lage en enkel strektegning av et hus. % Oppgave 4.2 a=[ ]; b=[ ]; plot(a,b) 106. Bruk Matlab til å tegne grafen til f (x) = x 3 1 over intervallet [ 1,1]. Legg så inn grafen til g (x) = 3x 2 i samme koordinatsystem, og velg forskjellig farge på de to grafene. % Oppgave 4.3 x=-1:0.05:1; plot(x,x.^3-1) hold on plot(x,3*x.^2, r ) 107. Bruk Matlab til å tegne grafen til funksjonen f (x) = sin 1 x over intervallet [ 1,1]. Bruk først skrittlengde langs x-aksen. Tegn grafen på nytt med skrittlengde % Oppgave 4.4 x=-1:0.01:1; plot(x,sin(1./x)) x=-1:0.0001:1; plot(x,sin(1./x)) 74
75 108. Lag en diary-fil og rediger den En følge er gitt ved a 1 = 1, a 2 = 3 og a n+2 = 3a n+1 2a n. Skriv et program som genererer de 30 første leddene i følgen. % Oppgave 8.1 a=zeros(1,30); a(1) = 1; a(2) = 3; for k=3:30 a(k) = 3*a(k-1)-2*a(k-2); 110. I denne oppgaven skal vi se på en modell for samspillet mellom rovdyr og byttedyr. Vi lar x n og y n betegne hhv. antall rovdyr og antall byttedyr etter n uker, og vi antar at x n+1 = x n (r + c y n ) y n+1 = y n (q dx n ) der r er litt mindre enn 1, q er litt større enn 1, og c og d er to små, positive tall. % Oppgave 8.2 x=zeros(1,1000); y=zeros(1,1000); r=0.98; q=1.04; c=0.0002; d=0.001; x(1)=50; y(1)=200; for k=2:1000 x(k) = x(k-1)*(r+c*y(k-1)); y(k) = y(k-1)*(q-d*x(k-1)); plot(1:1000,x,1:1000,y) a. Forklar tankegangen bak modellen b. Velg r = 0.98, q = 1.04, c = , d = 0.001, x 1 = 50, y 1 = 200. Lag et program som regner ut x n og y n for n Plott følgene x n og y n i samme koordinatsystem. Hvorfor er toppene til x n forskjøvet i forhold til toppene til y n? 75
76 111. En dyrestamme består av tre årskull. Vi regner med at 40% av dyrene i det yngste årskullet lever videre året etter, mens 70% i det nest yngste årskullet lever videre året etter. Ingen dyr lever mer enn tre år. Et individ i det andre årskullet blir i gjennomsnitt forelder til 1.5 individer som blir født året etter. Et individ i det eldste årskullet blir i gjennomsnitt forelder til 1.4 individer som blir født året etter. La x n, y n, z n være antall dyr i hvert årskull etter n år, og forklar hvorfor x n+1 = 1.5y n + 1.4z n y n+1 = 0.4x n z n+1 = 0.7y n % Oppgave 8.3 ab) x=zeros(100); y=zeros(100); z=zeros(100); x(1)=300; y(1)=0; z(1)=0; for n=1:99 x(n+1)=1.5*y(n)+1.4*z(n); y(n+1)=0.4*x(n); z(n+1)=0.7*y(n); plot(x, g ) hold on plot(y, r ) plot(z, b ) sum=x+y+z; x2=x./sum; y2=y./sum; z2=z./sum; % relativt plot figure(2) plot(x2, g ) hold on plot(y2, r ) plot(z2, b ) 76
77 a. Lag et program som regner ut x n, y n og z n for 1 n 100. Plott alle tre kurvene i samme vindu. Lag et nytt vindu der du plotter alle de relative bestandene x n = x n x n +y n +z n, y n = y n x n +y n +z n, z n = z n x n +y n +z n. b. Gjenta punkt a), men bruk andre startverdier, f.eks. x 1 = 300, y 1 = 0, z 1 =0. Sammenlign med resultatene i a). Gjør oppgavene a en gang med et nytt sett av startverdier. Ser du et mønster? c. La A = Forklar at x n y n z n = A n 1 x 1 y 1 z 1. Bruk dette til å regne ut x 100, y 100 og z 100 for starverdiene i a). Sammenlign med dine tidligere resultater. % Oppgave 8.3 c) A=[ ; ; ]; b=[300;0;0]; B=A^99; B*b 112. Determinanten til en 2 2-matrise er definert ved ( a b det c d ) = ad bc Lag en m-fil (en funksjonsfil) som regner ut slike determinanter. Filen skal ha ( ) a b inn-parametre a, b, c, d og ut-parameter det. c d % Oppgave 9.1 function ret=o0901(a,b,c,d) ret = a*d-b*c; 113. Skriv en funksjon som gir løsningen til ligningssystemet ax + by = e cx + d y = f 77
78 når det har en entydig løsning. Filen skal virke på denne måten: Inn-parametrene er koeffisientene a,b,c,d,e, f, og ut-parametrene er løsningene x, y. Dersom ligningssystemet ikke har en entydig løsning, skal programmet svare: Ligningssettet har ikke entydig løsning"(det behøver altså ikke å avgjøre om ligningssettet er inkonsistent eller har uelig mange løsninger). % Oppgave 09.2 function [x,y]=o0902(a,b,c,d,e,f) determinant = o0901(a,b,c,d); if determinant ~=0 v = [a b;c d]\[e; f]; x=v(1); y=v(2); else disp( Likningssettet har ikke entydig løsning ); 114. Lag en funksjon som regner ut leddene i følgen {x n } gitt ved: x n+2 = ax n+1 + bx n x 1 = c, x 2 = d Filen skal ha inn-parametre a,b,c,d,m og skal returnere de m første verdiene til følgen. % Oppgave 9.3 function ret=o0903(a,b,c,d,m) if (m >= 1) ret(1) = c; if (m >= 2) ret(2) = d; for (k=3:m) ret(k) = a*ret(k-1) + b*ret(k-2); 115. Lag en funksjon som regner ut leddene i følgen {x n } gitt ved: x n+1 = ax n (1 x n ) x 1 = b 78
79 Filen skal ha inn-parametre a, b, m, og skal returnere de m første verdiene til følgen. Sett m = 100, se på tilfellene b = 0.2 og b = 0.8, og kjør programmet for hhv. a = 1.5, a = 2.8, a = 3, a = 3.1, a = 3.5, a = 3.9. Plott resultatene. Eksperimenter videre hvis du har lyst, men behold humøret selv om du ikke finner noe mønster; fenomenet du ser på er et av utgangspunktene for det som kalles kaos-teori! % Oppgave 9.4 plot(oppg04(1.5,0.2,100)) figure(2) plot(oppg04(2.8,0.2,100)) figure(3) plot(oppg04(3,0.2,100)) figure(4) plot(oppg04(3.1,0.2,100)) figure(5) plot(oppg04(3.5,0.2,100)) figure(6) plot(oppg04(3.9,0.2,100)) figure(7) plot(oppg04(1.5,0.8,100)) figure(8) plot(oppg04(2.8,0.8,100)) figure(9) plot(oppg04(3,0.8,100)) figure(10) plot(oppg04(3.1,0.8,100)) figure(11) plot(oppg04(3.5,0.8,100)) figure(12) plot(oppg04(3.9,0.8,100)) function ret=oppg04(a,b,m) ret = zeros(1,m); if (m >= 1) ret(1) = b; for (k=2:m) ret(k) = a*ret(k-1)*(1-ret(k-1)); 79
80 116. Definer f (x) = sin x x som en linjefunksjon. Tegn grafen til f og regn ut integralet f fra 1 2 til 2. % Oppgave 10.1 f=inline( sin(x)./x ); x=linspace(0.5,2,100); plot(x,f(x)); 117. Gjenta oppgave 1, med definer nå f som en anonym funksjon. % Oppgave 10.2 f=@(x)sin(x)./x; x=linspace(0.5,2,100); plot(x,f(x)); 118. Definer f (x, y) = x 2 y y 2 som en linjefunksjon og tegn grafen. % Oppgave 10.3 f=inline( x.^2.*y-y.^2 ); r=linspace(-1,1,50); s=linspace(-1,1,50); [x,y]=meshgrid(r,s); mesh(x,y,f(x,y)); 119. Gjenta oppgave 3, med definer nå f som en anonym funksjon. % Oppgave 10.4 x=0.01:0.01:1; y=0.01:0.01:1; [x,y]=meshgrid(x,y); f=@(x,y)x.^2.*y-y.^2; mesh(x,y,f(x,y)); 120. Finn feilen og rett opp programmet: a=1:10; sum=0; for k=1:11 sum=sum+a(k); 80
81 121. Finn feilen og rett opp programmet: function fak=fakultet(n) fak=n*fakultet(n-1); 122. Finn feilen og rett opp programmet: A=[1 2 3; 4 5 6]; B=[1 2; 3 4]; A*B 123. Bruk Matlab til å regne ut: a b. 5/7 5/7 c ^ d. (2*3-4^2)/(13-2*2^2) e ^4 f. Hva er det 12. desimalet i 1/7? Hint: funksjonen floor er nyttig her. 81
82 x=1/7; x11=floor(x*1e11); x12=floor(x*1e12); tall=x12-10*x Lag følge variable: x = og y = e 1 og regn ut: x + y, x y, x y og sin x 2 y x=0.762 y=sqrt(9.56) + exp(-1) x+y x*y x/y sin(x^2*y) 125. Bytt om verdiene til variablene x og y uten at Matlab viser verdien til den temporære variabelen som du bruker. temp=x; x=y y=temp 126. Beregn antall sekunder i ett år. 365*24*60* Beregn avstanden x 2 + y 2 hvor x = 10 km and y = 50 km. x=10 y=50 dist=sqrt(x^2 + y^2) 128. Beregn volumet til Jorda og den gjennomsnittlige tettheten. Angi tettheten i kg/m 3. Jordas masse er kg og radiusen er 6371 km. 82
83 R=6371*1000; M=5.9737e+24; vol=4/3*pi*r^3; M/vol 129. a. La Matlab regne ut cos(θ) og sin(θ) for θ = 0,π/6,π/4,π/3 og π/2. Sjekk at resultatene er rimelige: Løsningsforslag: cos(0) = sin(π/2) = 1 cos(π/6) = sin(π/3) = cos(π/4) = sin(π/4) = cos(π/3) = sin(π/6) = 0.5 cos(π/2) = sin(0) = 0 b. Gjør om verdiene til θ fra radianer til grader. Hint: deg = rad 180 π. Regn ut verdiene ved å bruke funksjonene cosd(θ) og sind(θ). Får du samme svar som i a.? (Hvis ikke har du gjort noe feil.) Løsningsforslag: JA, du får samme svar! 130. La Matlab regne ut verdiene, og sjekk at resultatene er rimelige: e 1, 16, cosπ, sin π 6, tan π 4, arcsin 1 2, arctan1, cos45. exp(1) sqrt(16) cos(pi) sin(pi/6) tan(pi/4) asin(1/2) atan(1) cosd(45) 131. Anta at 1. januar er dag 1 i uke 1. I hvilken uke er dag 117? Løsningsforslag: Her vil vi at 1 til 7 skal gi uke 1, 8 til 14 uke 2, osv. Da kan vi dele med 7 og avrunde oppover. Vi sjekker først at det fungerer som vi vil ved å teste med dagene 1, 7 og 8. ceil(1/7) 83
84 ceil(7/7) ceil(8/7) uke=ceil(117/7) Svaret er Anta at 1. januar er dag 4 i uke 1. I hvilken uke er dag 117? Løsningsforslag: Her må vi legge til 3 dager i formelen for de som mangler i den første uken: uke = ceil((117+3)/7) Svaret er Vi antar at en bakteriepopulasjon vokser eksponentielt og har en vekst gitt ved P = P 0 e kt der t er tiden i sekunder, P 0 = 120 er antall bakterier ved t=0 og k = 0.04s 1. Finn ut hvor mange bakterier det er etter: a. 10 sekunder Løsningsforslag: 179 b. 30 sekunder Løsningsforslag: 398 c. 1 minutt Løsningsforslag: d. 1 time Løsningsforslag: (Jordskjelv). Jordskjelvet på Haiti i 2010 målte 7.0 Mw (Moment magnitude scale) og det i Chile ca en måned senere 8.8 Mw forskjellen i energi for to jordskjelv kan beskrives ved E = (m 1 m 2 ) Hvor mange ganger mer energi ble utløst i jordskjelvet i Chile enn i det på Haiti? Løsningsforslag: 501 ganger mer 135 (Aldersbestemmelse etter Karbon-14 metoden). Karbon-14 er en radioaktiv isotop med halveringstid på 5730 år. I atmosfæren er det et nokså konstant blandingsforhold mellom karbon-14 og vanlig karbon 12. Dette forholdet kaller vi I 0. Når dyr og planter dør vil de ikke lengre ta opp karbon-14 og mengden av karbon-14 de inneholder blir gradvis redusert, mens mengden av karbon-12, som ikke er radioaktivt, blir uforandret. Forholdet mellom karbon-14 og karbon- 12 i prøven av det døde dyret/planten kaller vi I. Tiden t er antall år som har gått siden dyret/planten vi ser på døde. Sammenhengen mellom I 0, I og t er gitt ved: t = ln(i /I 0) ln
85 Bruk Matlab til å regne ut alderen på følge prøver: a. En tann fra en sabeltanntiger der I er ca 10% av I 0 Løsningsforslag: år b. En tann fra en mammut der I er ca 5% av I 0 Løsningsforslag: år c. En trebit der forholdet mellom I og I 0 er 50% Løsningsforslag: 5730 år d. Et maleri der I er ca 96% av I 0. Fra hvilken epoke er dette maleriet? Løsningsforslag: 337 år. Barokken (1674) 136. Når en lydbølge går fra et medium til et annet res både hastigheten til bølgen og retningen. Snells brytningslov uttrykker dette forholdet ved sammenhengen v1sin(θ 2 ) = v2sin(θ 1 ), der størrelsene er angitt på figuren under. Vi skal se på en lydbølge som går fra luft til vann. Lydhastigheten i luft er 340m/s, mens lydhastigheten i vann er 1500m/s. Løsningsforslag: Kode som løser oppgaven blir 85
86 v1 = 340; v2 = 1500; theta1=10; theta2= asind(v2/v1*sind(theta1)); t= 5; s= v2*t; dybde=s*cosd(theta2); x=sqrt(s^2-dybde^2); x2 = s*sind(theta2); a. Vi antar at θ 1 = 10. Finn θ 2 Løsningsforslag: θ 2 = 50 b. Vi kan uttrykke lengden bølgen tilbakelegger i vannet med formelen: s = vt, der v = 1500 m/s. Finn ut hvor langt lydbølgen beveger seg i løpet av 5 sek etter den traff vannet. Løsningsforslag: t=5 gir s=7500m c. Finn ut hvor dypt ned (langs z-aksen) bølgen har beveget seg i vannet. Løsningsforslag: 4820m d. Finn ut hvor langt bortover (langs x-aksen) bølgen har beveget seg ved hjelp av Pythagoras læresetning. Finnes det en annen metode å regne ut denne lengden på? Løsningsforslag: 5746m, Ja man kan bruke s*sind(θ 2 ). x og x2 i løsningsforslaget gir samme svar 137. Gitt følge kode: for i=1:6 num = i; a. Hvor mange steg er det i løkka? Løsningsforslag: 6 b. Hvilken verdi har num etter at løkka er ferdig? Løsningsforslag: 6 86
87 c. Hvilken verdi har num etter at løkka har gått 3 ganger? Løsningsforslag: (Flervalgsoppgave, kun ett riktig svar). For å få noe ut av oppgaven bør den gjøres uten å bruke Matlab. tallet=10; for k=2:6 tallet = tallet+k/2; tallet Hva skrives ut? tallet = 10 tallet = 20.5 tallet = 20 tallet = 30 tallet = 0 Løsningsforslag: 20 er riktig svar Vi skal bruke Matlab til å studere partall og oddetall. Lag en løkke som skriver ut de n første oddetallene. Sett n lik et tall i begynnelsen av programmet. n=10; for k=1:n disp(2*k-1) 140. Skriv en for-løkke som finner de n første kvadrattallene. n=10; for k=1:n disp(k^2) 141. Man definerer fakultet av n til n! = n. Skriv en for-løkke som regner ut n!. Sett verdien til n helt i starten av programmet. n=10; 87
88 val=1; for k=2:n val=val*k; disp(val) 142. Din nye PC har kostet 2000 kroner. Den devalueres med 20% hvert år. a. Hvor mye blir PC en verdt når du får bachelorgraden din om 3 år? val=2000; for k=1:3 val=val*0.8; disp(val) b. Skriv om programmet slik at PC en i stedet devalueres med 20% av den opprinnelig verdien hvert år (det vil si at vi devaluerer med et fast beløp hvert år, i motsetning til i a.). val=2000; deval=val*0.2; for k=1:3 val=val-deval; disp(val) 143. Du har 1000 kroner på bankkontoen din. Banken din tilbyr fast rente på 5% per år. a. Bruk en for-løkke til å beregne hvor mye du har på kontoen om 10 år. sumpenger1=1000; for k=1:10 sumpenger1=sumpenger1*1.05; sumpenger1 88
89 Kjører du koden vil du se at vi sitter igjen med 1629kr etter 10 år med den første banken b. En annen bank tilbyr deg en rente på 4% per år de 5 første årene og 6% per år de 5 siste årene. Hvor mye kan du tjene ved å bytte bank? sumpenger2=1000; for k=1:5 sumpenger2=sumpenger2*1.04; for k=6:10 sumpenger2=sumpenger2*1.06; sumpenger2 diffpeng=sumpenger2-sumpenger1; disp(diffpenger) Vi sitter igjen med 1628kr etter 10 år med den andre banken. Det er derfor ikke lønnsomt å bruke den andre banken En vanntank inneholder 10 liter usaltet vann på dag 0. I forbindelse med et eksperiment i oseanografi, blir det tilført 1dl salt hver dag fra dag 1. Samtidig, fordampes 2dl usaltet vann hver dag. Regn ut hvordan forholdet salt/vann varierer i løpet av den første uken. vannmengde=10; saltmengde=0; for k=1:7 saltmengde=saltmengde+0.1; vannmengde=vannmengde-0.2; forhold=saltmengde/vannmengde; disp(forhold) 145 (Flervalgsoppgave, kun ett riktig svar). For å få noe ut av oppgaven bør den gjøres uten å bruke Matlab. tallet=0; for i=1:2 for j=2:3 89
90 tallet = tallet+i+j; tallet Hva skrives ut? tallet = 7 tallet = 0 tallet = 11 tallet = 16 tallet = 5 Løsningsforslag: 16 er riktig svar Vi skal se på en av de store innsjøene i Norge. Anta at vanntilførselen fra elvene i området, V 0, var 128 m 3 /s i år Pga. økt bresmelting økte tilførselen med 4% pr. år frem til a. Finn V 0 i m 3 /år i Løsningsforslag: m 3 /år. b. Hvor stor var V 0 i 2009? Løsningsforslag: m 3 /år. c. Anta videre at i tillegg er det tilsig fra grunnvannet. Det var V G = 0.8 km 3 /år i 2003 og ble redusert med 3% pr.år. Regn ut total tilførsel av vann til innsjøen i 2004 og i Løsningsforslag: i 2004: V = V V G 0.97 = m 3 /år. i 2009: V = V V G 0.97 ( ) = m 3 /år Legg inn disse vektorene i Matlab: (1, 9,7,5, 7), (π, 14,7/3), (1,3,5,7,9,...,99), (124,120,116,112...,4,0). : a=[1,-9,7,5,-7] b=[pi,-14, 7/3] c=1:2:99 d=124:-4: Legg inn arrayet (1, 2, 4, 8, 16, ) Matlab og finn summen. Hint: 4096 = : 90
91 a=0:12; a=2.^a; summen=sum(a) NB: Ikke kall summen sum siden sum ogsâ er navnet pâ en innebygd funksjon Definer vektorene A, B, og C slik at de har f lge verdier i Matlab: A=[ ] B=[ ] C=[0.5,1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5] A=1:9; B=2:2:18; C=0.5:0.5:5; D=B.^2-A.^2 a. PÂ hvilken plass i hhv. A, B, og C finner du tallet 4? Løsningsforslag: plass 4, 2 og 8 b. Hvilken av vektorene er lengst? Løsningsforslag: C er lengst c. Opprett vektoren D=B.^2-A.^2. d. Hva blir A + B +C + D? Løsningsforslag: Vi fâr enfeilmelding fordi alle vektorene ikke har samme lengde 150. Definer a=[ ]. Lag et program som beregner sum(a) ved hjelp av en l kke istedenfor funksjonen sum. a=1:10; summen=0; % initialisere for i=1:length(a) summen=summen+a(i); 91
92 151. Trykket (p) i en gitt h yde (z) i atmosfêren uttrykkes ved p(z) = p 0 e ( z H ), hvor p 0 er bakketrykket, z er h yden over bakken og H en karakteristisk konstant. Vi kan bruke f lge verdier pâ disse: p 0 = 1004 [hpa] H = 7800 [m] a. Opprett et array Z, med h yder 0-20km med intervall pâ 500m b. Finn trykket for alle h ydene og lagre dem i et array P z : P0=1004; % trykk ved bakken i hpa H=7800; % konstant i m z=0:500:20000; % h yder i m Pz=P0*exp(-z/H) Pass pâ at h ydene og konstanten er enten begge i meter eller begge i kilometer 152. I denne oppgaven skal vi se pâ hvordan vi kan skrive ut oddetall, partall, og kvadrattall. R=1:2:49; P=2:2:50; S=P-R; length(s) prod(s) sum(s) prod(p./r) sum(1./p) a. Opprett en vektor R med alle oddetallene mellom 0 og 50 og et array P med alle partallene f.o.m. 2 t.o.m. 50 b. Lag en vektor S = P - R. Hvor lang er S? Hva blir produktet av alle elementene i S? Hva blir summen av alle elementene i S? Løsningsforslag: 25, 1, 25 c. Hva blir produktet av elementene i P R? Løsningsforslag:
93 d. Hva blir summen av 1 P? Løsningsforslag: Finn tettheten til 4 forskjellige steintyper pâ nettet, sett verdiene i en vektor og konverter fra g /cm 3 to kg /m 3. % basalt, granite, sandstone, purnice from a=[ ] a=a* Det magnetiske feltet i Oslo i 2010 har de tre komponentene B N = , B E = og B Z = hvor verdiene er gitt i nanotesla og B N er feltintensitet mot nord, B E mot st, og B Z vertikalt nedover. Sett de tre elementene i et array. Deretter beregn deklinasjon D og inklinasjon I av feltet som er relatert til feltkomponentene ved formlene tand = B E /B N og tan I = B Z / B 2 N + B 2 E. B=[ ,484.7, ] % mag felt i Oslo i nt declin=atand(b(2)/b(1)) % declination in degrees inclin=atand(b(3)/sqrt(b(1)^2+b(2)^2)) % inclination in degrees 155 (Flervalgsoppgave, kun ett riktig svar). For  fâ noe ut av oppgaven b r den gj res uten  bruke Matlab. A = [ ] B = [5 6 8] Operasjonen C = A + B gir C = [ ] Operasjonen C = A + B gir C = [ ] Operasjonen C = [A,B] gir C = [ ] Operasjonen C = [A + B] gir C = [ ] Løsningsforslag: Det tredje alternativet er riktig. 156 (Flervalgsoppgave, kun ett riktig svar). For  fâ noe ut av oppgaven b r den gj res uten  bruke Matlab. tallet=0; for i=1:2 for j=2:3 tallet = tallet+i+j; tallet 93
94 Hva skrives ut? tallet = 7 tallet = 0 tallet = [ ] tallet = 16 tallet(i,j) = [ ] Løsningsforslag: 16 er riktig. 157 (Flervalgsoppgave, kun ett riktig svar). For  fâ noe ut av oppgaven b r den gj res uten  bruke Matlab. A = [ ] B = [6 7 8] Operasjonen C = A B gir C = [ ] Operasjonen C = A B(1) gir C = [ ] Operasjonen C = B A gir C = [ ] Operasjonen C = [A,B] gir C = [ ] Løsningsforslag: Det andre alternativet er riktig. 158 (Flervalgsoppgave, kun ett riktig svar). For  fâ noe ut av oppgaven b r den gj res uten  bruke Matlab. D = [ ] E = [2 2 2] Operasjonen F = D. E gir F = [ ] Operasjonen F = D E gir en matrise. Operasjonen F = D. E(1) gir F = [ ] Operasjonen F = E. D(4) gir F = [4 4 4] Løsningsforslag: Det fjerde alternativet er riktig Gitt f lge kode: for i=1:3 num = i; obs(i)= num; a. Hva slags type variabel er obs? Løsningsforslag: obs er en array b. Hvilke(n) verdi(er) har obs nâr l kka er ferdig? Løsningsforslag: [1 2 3] 94
95 c. Hva er summen av obs? Løsningsforslag: Gitt f lge array F = [ ] F inneholder gjennomsnittstemperatur for hver mâned pâ Blindern gitt i Fahrenheit. Formelen for  konvertere fra Fahrenheit til Celsius er gitt ved C = (F 32)/1.8. Bruk en for-l kke og lag en ny array C som inneholder tilsvare temperaturer i Celsius. F = [ ]; for i=1:length(f) C(i)=(F(i)-32)/1.8; 161. Fibonacci-tallene er en tallf lge der hvert tall er summen av de to forrige tallene i f lgen: osv a. Lag en l kke som lager de femten f rste Fibonaccitallene, og legger dem i et array kalt Fibo. Fibo = zeros(1,15); Fibo(1) = 0; Fibo(2) = 1; for i = 3:15 Fibo(i) = Fibo(i-1) + Fibo(i-2); Her mâ vi f rst lage et array for tallene med femten elementer der f rste element inneholder tallet 0 og det andre elementet tallet 1. S gâr vi i l kke der vi starter pâ element 3 og beregner verdien pâ elementet ut fra de to foregâe elementene som vi lagrer i element nr. i. b. Lag en l kke der du finner Fibonaccitall nr. n. Du velger verdien til n i begynnelsen av programmet. Du skal ikke lage en vektor som i a., bare finne tall nr n. 95
96 n = 15; f1 = 0; f2 = 1; for i = 3:n f3 = f2 + f1; f1 = f2; f2 = f3; disp(f3); Vi velger 15 som tallet n og legger dette i en variabel. Dette gj r det lettere  re pâ tallet senere. S initaliserer vi to variable f1 og f2 til verdi 0 og 1. S gâr vi i en l kke der i varierer fra 3 til n og beregner Fibonacci tallet nr. i som vi legger i variablen f3. Videre tar vi vare pâ det nest siste tallet i f1 og det siste som vi nâ har i f3 legges i f2. Da er vi klar for neste runde i l kka. c. Vanskelig: Du fâr oppgitt at tallene pâ plass nr. 16 og 17 i Fibonaccitallrekka er henholdsvis 610 og 987. Bruk kun denne informasjonen til  regne ut rekka bakover fra tall nr 17. Legg disse tallene inn i et array.(arrayet du fâr burde vêre lik den du fikk i oppgave 1. pluss de to tallene du fikk opgitt i denne oppgaven.) Fibo = zeros(1,17); Fibo(17) = 987; Fibo(16) = 610; for i = 15:-1:1 Fibo(i) = Fibo(i+2) - Fibo(i+1); Her mâ vi snu pâ mâten vi gjennoml per l kka. Vi starter med i = 15 siden vi skal bruke verdiene pâ plass 17 og 16 til  beregne den neste verdien nedover i arrayet. Vi initaliserer element 16 og 17 til de angitte verdiene. Da er det bare  strte beregningene for element i ut fra de to vediene pâ plass i + 1 og i + 2 ved en enkel subtraksjon I Oppgave 141 i Seksjon?? definerte vi fakultet av n til  vêre n! = n, og programmerte en l kke som regnet ut n!. Skriv om l kken slik at alle fakultetverdiene fra 1! til n! lagres i et array som du kaller fakultet. 96
97 n = 10; fakultet = zeros(1,n); fakultet(1) = 1; for i = 2:n fakultet(i) = fakultet(i-1) * i; Her velger vi n = 10 og setter av plass for et array pâ 10 elementer med verdi 0. Vi initaliserer f rste element til 1 og starter l kka med indeks til element 2. Vi bruker foregâe element til  beregne verdien av element i En tallf lge er gitt ved a 1 = 1, a 2 = 3 og a n+2 = 3a n+1 2a n. Skriv et program som returnerer en vektor med de 8 f rste leddene i f lgen. n=8; % antall elementer som skal beregnes a=zeros(1,n); % initialisere arrayen a(1)=1; a(2)=3; for i=3:n a(i)=3*a(i-1)-2*a(i-2); eller n=8; % antall elementer som skal beregnes a=zeros(1,n); % initialisere arrayen a(1)=1; a(2)=3; for i=1:n-2 a(i+2)=3*a(i+1)-2*a(i); 164. Legg inn vektorene a = (3,1, 2,5,4,3) og b = (4,1, 1,5,3,1) i Matlab, og utfør kommandoen» plot(a,b). Utfør også kommandoene» plot(a) og» plot(b), og bruk» hold on til å sørge for at de to siste figurene kommer i samme vindu. a=[ ]; b=[ ]; plot(a,b) 97
98 figure hold on plot(a) plot(b) hold off 165. Plot de to funksjonene f (x) = e 0.5x2 og h(x) = e (x 3t)2. La x variere fra 4 til 4 med små skrittlengde (prøv deg frem til du faa fine glatte grafer). t skal være et tall mellom 0 og 2. Plott de to funksjonene i samme figur. La de ha ulik farge. Prøv ut forskjellige verdier av t. Hva gjør t? x=linspace(-4,4,1000); f=exp(-0.5*x.^2); t=0.5; h_xt=exp(-(x-3*t).^2); figure(1) plot(f) hold on plot(h_xt, g ) t forflytter senteret av funksjonen, eller forflytter bølgetoppen". 166 (To vulkaner). Vi kan se for oss en vulkan som en sylinder og beskrive dens utslippsrate av magma ved Q = πr4 P 8µL m3 /s Der L er lengden i meter, R radiusen i m, µ viskositeten til magmaen i Pa/sek og P trykket i vulkanen gitt i Pa. For en vulkan fra Hawaii og Mount St Helen under typiske utbrudd: L H = 5000 L St = 7000 µ H = 100 µ St = R H = 1m L St = 50 P H = P St = a. Hvilken vulkan slipper ut mest magma under et typisk utbrudd? Løsningsforslag: Følge kode løser problemet: L = [ ]; u = [100 2*10^6]; R = [1 50]; P = [5*10^6 3*10^7]; Q = (pi*r.^4.*p)./(8*u.*l); 98
99 Vulkanen på St. Helens slipper ut mest (St.Helens: e+03, Hawaii: ) b. Hvor stort trykk ville man trengt i vulkanen på Hawaii for at de to vulkanene skulle slippe ut like mye magma? Pp = P(1)/Q(1)*Q(2); som gir at trykket på Hawaii vulkanen må være minst e+09 Pa for å slippe ut samme mengde magma. c. Plott Q som funksjon av radier og lengder i nærheten av de gitte verdier, hva er de viktigste faktorene for hvor mye lava som blir sluppet ut? R = 1:50; L = 5000; u = 100; P = 5*10^6; Q = (pi*r.^4*p)/(8*u*l); figure(1); plot(r,q); xlabel( Radius [km] ); ylabel( Lavaflom ); clear R L Q; R = 1; L = 5000:100:7000; Q = (pi*r.^4*p)./(8*u*l); figure(2); plot(l,q); xlabel( Radius [km] ); ylabel( Lavaflom ); Ut fra plottene ser vi at det er radius som er den viktigste faktoren for mengden av lava som str mmer ut Vi skal se litt mer på oppgaven fra tidligere der vi hadde en bakteriepopulasjon som vokste eksponentielt og hadde en vekst gitt av P = P 0 e kt der t er tiden i sekunder, P 0 =120 er populasjonen ved t = 0 og k =
100 t=0:30; % tidsrekka k=0.04; % parameter P0=120; % bakteriepopulasjonen ved start P=P0*exp(k*t); figure(1) plot(p) xlabel( tid [s] ) ylabel( antall bakterier ) title( Populasjon ) xlim([1 30]) t=1:60*6; P=P0*exp(k*t); figure(2) hold on plot(p) xlabel( tid [s] ) ylabel( antall bakterier ) title( Populasjon ) plot(t,1e8, r* ) xlim([1 360]) hold off Tidspunktet naar populasjonen naar grensen er ved ca. 340 sekunder. a. Lag en tidsvektor for de 30 første sekundene som du kaller t. b. Regn ut bakteriepopulasjonen for hver t, og plot denne. Sett navn på aksene. c. Lag en ny tidsvektor som representerer 6 minutter. d. Regn ut bakteriepopulasjonen for hvert sekund i 6 minutter, og plot denne. Sett navn på aksene e. Plot en linje i figuren din som markerer der populasjonen når 10 8 bakterier. La linjen være røde stjerner. Les av for hvilken t denne verdien nås. 100
101 168. Bruk kommandoen» plot til å lage en enkel strektegning av et hus. x=[ ]; y=[ ]; plot(x,y) % definere aksene for  se huset bedre figure plot(x,y) axis([ ]) 169. Bruk Matlab til å tegne grafen til f (x) = x 3 1 over intervallet [ 1,1]. Legg så inn grafen til g (x) = 3x 2 i samme koordinatsystem, og velg forskjellig farge på de to grafene. Bruk skrittlengde langs x-aksen. x=-1:0.01:1 figure hold on y=x.^3-1 plot(x,y, r ) y=3*x.^2 plot(x,y, g ) hold off 170. Skriv inn realistiske verdier til nedbør på 7 dager i et array og lag et søylediagram som viser nedbør som en funksjon av tid (med bar). Lag også et histogram av verdiene (med hist). Prøv deg frem med forskjellige verdier av n. ned=[ ]; subplot(2,2,1) bar(ned) title( bar ) subplot(2,2,2) hist(ned) title( hist default ) subplot(2,2,3) hist(ned,2) title( hist 2 ) subplot(2,2,4) hist(ned,4) 101
102 title( hist 4 ) 171. Om man kaster en ball vil den følge en bane gitt av formelen: f (x) = x tan(θ) 1 g x 2 2v0 2 cos 2 (θ) + y 0 der v 0 er startfarten (i m/s), θ er vinkelen du kaster ballen i forhold til x-aksen, y 0 er høyden ballen kastes i (ved x=0) og g er tyngdeakselerasjonen. Figur 5: En balls bane gjennom luften i Oppgave 171 Du kan sette g = 9.81m/s 2. Prøv ulike startverdier og lag figurer som viser banen til ballen. Hint: om du setter θ i grader må du bruke tand() og cosd(). v0=80; theta=60; x=0:0.01:10; g=9.81; y0=2; y=x*tand(theta)-((g*x.^2)/(2*v0*(cosd(theta))^2))+y0; plot(y) hold on ylim([0 max(y)]) 102
103 172 (Meteorer). Vi skal se på energien i meteorer som treffer månen og størrelsen på krateret de lager. a. Den kinetiske energien til masse i bevegelse er K E = 1 2 mv 2 der K E er energien i Joule, m er massen i kg og v hastigheten i m/s. Hva er den kinetiske energien til en meteor på 5 g som beveger seg med v = 71 km/s (typisk hastighet i asteroidebeltet)? K_e =.5*0.005*32000^2; % = 1.26*10^7 Joule b. En ligning som blir brukt for å beregne diameteren på kratere på månen er der D at er Diameteren i meter, D at = 0.015ρ 1 6 p ρ 1 2 t W.37 sinφ 2 3 ρ p = 600 og ρ t 3000 er henholdsvis meteorens og månens tetthet i kg/m 3, W er prosentandelen av kollisjonsenergien som går med til å lage et krater, og φ er vinkelen på nedslaget i grader. Bruk W = 0.9K E, φ = 90 til å regne ut diameteren til krateret meteoren fra a. ville laget. ro_p = 600; % kg/m^3 ro_t = 3000; % kg/m^3 W =.9*K_e; % J i=90; D_at =.015*ro_p^(1/6)*ro_t^(-.5)*W^(.37)*sind(i)^(2/3); % 0.32 m c. ρ p = 600 er et ca. anslag, vis enten ved plott eller på andre måter hvordan kraterdiameteren avhenger av tettheten til meteoren og månen ved å variere ρ p og ρ t innenfor rimelige verdier (hvor stort ville krateret blitt 103
104 dersom den var av feks is, jern, bly, gull?). Løsningsforslag: ρ i s = 920 D a t = 0.34m ρ j er n = 7870 D a t = 0.49m ρ bl y = D a t = 0.52m ρ g ull = D a t = 0.57m d. La nå ρ p = 5000 men la den totale massen variere fra 1 g til 100 kg, og plott kraterstørrelsen som funksjon av vekten til meteoren. Husk å sette verdier på aksene. Hint: logspace(-3,2, 100) generer 100 verdier mellom 10 3 og 10 2 med logaritmisk avstand. Det går også an å bruke linspace her. v=logspace(-3,2, 100); W2=.9*.5.*v.*71000^2; D2=.015*ro_p^(1/6)*ro_t^(-.5).*W2.^(.37).*sind(i)^(2/3); plot(v,d2) e. Denne formelen gjelder strengt tatt kun for mindre kratere på månen, men vi kan teste hvor stor asteroiden som laget Chicxulub krateret på Yucatan halvøya må ha vært etter denne formelen. Krateret har en radius på 180 km og mange mener at det er dette nedslaget som utslettet dinosaurene. Bruk ρ t = 6000, ρ p = 3000 og resten som i b. og beregn massen. Hva med radiusen? Virker resultatene sannsynlig? Løsningsforslag: ca mass = 8*10^12 r = sqrt(m/(4*pi*ro)) % = ca 14 km som er ca 3x for stort stort I denne oppgaven skal vi se på en modell for samspillet mellom rovdyr og byttedyr. Vi lar x n og y n betegne hhv. antall rovdyr og antall byttedyr etter n uker, og vi antar at x n+1 = x n (1 r + c y n ) y n+1 = y n (1 dx n + q) der r, q, c og d er små, positive tall. a. Forklar tankegangen bak modellen. 104
105 b. Velg r = 0.02, q = 0.04, c = , d = 0.001, x 1 = 50, y 1 = 200. Lag et program som regner ut x n og y n for n Plott følgene x n og y n i samme koordinatsystem. Hvorfor er toppene til x n forskjøvet i forhold til toppene til y n? % rovdyr og byttedyr % antall dyr i en uke = antall dyr uka f r - de d de + de nyf dte % antall nyf dte rovdyr avhengig av antall byttedyr % antall d de byttedyr avhengig av antall rovdyr nt=1000; % antall uker r=0.02; % def av f dselsrater og d delighetrater q=0.04; c=0.0002; d=0.001; x=zeros(1,nt); y=zeros(1,nt); x(1)=50; % initialisering antall rovdyr y(1)=200; % initialisering antall byttedyr for n=2:nt x(n)=x(n-1)*(1-r+c*y(n-1)); y(n)=y(n-1)*(1-d*x(n-1)+q); figure hold on plot(x, r ) plot(y, b ) title( antall rovdyr (r d) og byttedyr (blâ) ) hold off % er det mange byttedyr, ker antall rovdyr; er det fâ byttedyr, minker antall rovdyr 174. En dyrestamme består av tre årskull. Vi regner med at 40% av dyrene i det yngste årskullet lever videre året etter, mens 70% i det nest yngste årskullet lever videre året etter. Ingen dyr lever mer enn tre år. Et individ i det andre årskullet blir i gjennomsnitt forelder til 1.5 individer som blir født året etter. Et individ i det eldste årskullet blir i gjennomsnitt forelder til 1.4 individer som blir født året 105
106 etter. La x n, y n, z n være antall dyr i hvert årskull etter n år, og forklar hvorfor x n+1 = 1.5y n + 1.4z n y n+1 = 0.4x n z n+1 = 0.7y n a. Anta at det er 100 dyr av hvert årskull det første året. Lag et program som regner ut x n, y n og z n for 1 n 100. Plott alle tre kurvene i samme vindu. Lag et nytt vindu der du plotter alle de relative bestandene x n = x n x n +y n +z n, y n = y n x n +y n +z n, z n = z n x n +y n +z n. b. Gjenta a., men bruk andre startverdier, f.eks. x 1 = 300, y 1 = 0, z 1 = 0. Sammenlign med resultatene i 1. Gjør oppgavene a en gang med et nytt sett av startverdier. Ser du et mønster? : %oppgave med 3 Ârskull % x er antall yngste, y antall mellomste, og z antall eldste % indeksen k representerer hvilket Âr man er i. nt = 100; %antall Âr x=zeros(1,nt); y=zeros(1,nt); z=zeros(1,nt); x(1)=100; % initialisering antall dyr y(1)=100; z(1)=100; for k=2:nt % regne ut utviklingen x(k)=1.5*y(k-1)+1.4*z(k-1); y(k)=0.4*x(k-1); z(k)=0.7*y(k-1); figure hold on plot(x, : ) plot(y, -- ) plot(z, - ) %beregne og plotte de relative bestandene xr=x./(x+y+z) yr=y./(x+y+z) 106
107 zr=z./(x+y+z) figure hold on plot(xr, : ) plot(yr, -- ) plot(zr, - ) 175. For å finne vinkelen til sola, θ 0, i forhold til et sted på jorda må man ta hensyn til tre vinkler. De er breddegrad, timevinkel og deklinasjonsvinkel. Breddegraden kalles φ og sier hvor langt nord-syd vi er i forhold til ekvator. Timevinkelen, h, forteller oss hvilken tid på døgnet det er. Timevinkelen er lik null midt på dagen, og man legger til 15 grader(evt trekker fra) for hver time etter 12 (for hver time tidligere enn 12). Deklinasjonsvinkelen, δ, forteller om helningen til jorda i forhold til sola. Den er størst ved sommer- og vintersolverv, ±23.45 grader, og 0 ved høst-og vårjevndøgn. Formelen for å regne ut θ 0 er som følger: cos(θ 0 ) = sin(φ)sin(δ) + cos(φ)cos(δ)cos(h) a. Regn ut θ 0 for følge steder: 1. Oslo: 60N, kl 15.00, ved sommersolverv 2. New York City: 40N, kl 09.00, ved høstjevndøgn 3. Singapore: 1N, kl ved vårjevndøgn Løsningsforslag: Følge kode løser problemet: 1. Oslo: 60 N kl. 15:00, sommersolhverv f = 60; h = 45; delta = 23.45; Theta0 = asind(sind(f)*sind(delta) +cosd(f)*cosd(delta)*cosd(h)); og da er vinkelen θ New York: 40 N kl. 15:00, h stjevnd gn f = 40; h = -45; delta = 0; Theta0 = asind(sind(f)*sind(delta) +cosd(f)*cosd(delta)*cosd(h)); 107
108 og da er vinkelen θ Singapore: 1 N kl. 12:00, vârjevnd gn f = 1; h = 0; delta = 0; Theta0 = asind(sind(f)*sind(delta) +cosd(f)*cosd(delta)*cosd(h)); og da er vinkelen θ 89 b. Nå skal vi se litt nærmere på når sola går opp og ned i Oslo og Tromsø: Oslo ligger 60N, mens Tromsø ligger 69N. I løpet av ett døgn varierer timevinkelen fra -180 ved midnatt til 180 ved midnatt ett døgn etter. Den skal være lik null kl Timevinkelen øker 15 grader pr. time. 1. Lag et array med lengde 24 som inneholder timevinklene fra midnatt til midnatt ett døgn senere. Hint: la timevinkelen variere fra -165 til 180, med skritt på La det være sommersolverv. Regn ut solvinklene for ett døgn for både Oslo og Tromsø. Plot resultatet i samme figur. Husk navn på aksene! 3. Plot en linje for θ 0 lik 90 i samme figur som i 1. Hva representerer denne linja? 4. Finn ut når sola går opp i Oslo og i Tromsø, og når den går ned. 5. Hvorfor er ikke θ 0 lik null midt på dagen? 6. La det så være vintersolverv. Gjør tilsvare som i oppgave 1) til 4) 7. Hvorfor får Tromsø så ekstreme verdier i forhold til Oslo? Løsningsforslag: Soloppgang og solnedgang i Oslo og Tromsø: 1. Følge kode løser problemet: h = -165:15:180; 2. Følge kode løser problemet: h = -165:15:180; f = 60; delta = 23.45; ThetaOslo = asind(sind(f)*sind(delta) +cosd(f)*cosd(delta)*cosd(h)); f = 69; 108
109 ThetaTromso = asind(sind(f)*sind(delta) +cosd(f)*cosd(delta)*cosd(h)); hold on plot(thetaoslo); plot(thetatromso, r ); axis tight xlabel( Tid [24 timer] ); ylabel( Solvinkelen ); Title( Solvinkel for Oslo og Troms ); 3. Følge kode løser problemet: x = 1:24; plot(1:24,90, k* ); ylim([ ]); 4. Vi ser av figuren at Oslo har soloppgang ca. kl 03:00 og solnedgang ca. kl. 21:00. Tromsø har midnattssol og har derfor ikke soloppgang og solnedgang. 5. θ 0 er null bare ved ekvator. I Norge står sola i sør kl. 12: Her rere vi bare på delta variablen og gir den verdien grader før vi kjører programmene på nytt. 7. Fordi Tromsø ligger nord for polarsirkelen. c. Vi skal nå la timevinkelen være konstant lik null, dvs. at det er midt på dagen. Nå skal deklinasjonsvinkelen variere gjennom et helt år. Vi starter på sommersolverv. Deklinasjonsvinkelen pr. dag kan regnes ut vha: δ = cosd(m), der m = 0 : 360/364 : Regn ut hvordan solvinkelen for Oslo varierer i løpet av ett år. Gjør tilsvare beregninger for Tromsø. Plot resultatet i samme figur. 2. Hvor mange dager er uten sol i Tromsø? Har vi tilsvare dager i Oslo? Om du synes dette er gøy, gjør gjerne tilsvare oppgaver med andre byer. Informasjon om breddegrad finner du lett på Wikipedia. Løsningsforslag: Konstant timevinkel på 0 grader. 1. Følge kode løser problemet: 109
110 h = 0; f = 60; m = 0:360/364:360; delta = * cosd(m); ThetaOslo = asind(sind(f)*sind(delta) +cosd(f)*cosd(delta)*cosd(h)); f = 69; ThetaTromso = asind(sind(f)*sind(delta) +cosd(f)*cosd(delta)*cosd(h)); hold on plot(thetaoslo); plot(thetatromso, r ); axis tight xlabel( Dager [365] ); ylabel( Solvinkelen ); Title( Solvinkel for Oslo og Troms ); xlim([1 365]); ylim([ ]); plot(1:360,90, k ); 2. Tromsø har 53 dager uten sol og Oslo har ingen dager uten sol siden Oslo er sør for polarsirkelen. Vi kan lese dette ut fra figuren eller bruke en funksjon som heter find samt length slik length(find(thetatromso <= 0)) som gir antall dager der solvinkelen er mindre eller lik null (mørketid) I denne oppgaven skal vi lage flere arrayer vi kan få bruk for. a. Lag et array x som går fra 0 til 2π, med 1000 punkter. Lag en figur der du plotter funksjonen S=sin(x). Løsningsforslag: Følge kode løser problemet: x = linspace(0,2*pi,1000); S = sin(x); plot(s); b. Man kan tilnærme funksjonen sin(x) med summen S m (x) = m j =0 110 ( 1) j 2j +1 x (2j + 1)!,
111 der m er antall ledd i summen. Regn ut denne summen fra null til en gitt verdi m, som du setter i begynnelsen av programmet. m kan ha alle mulige positive verdier, men vi skal bruke verdier mellom 1 og 10. Bruk arrayen x som du definerte i a.. Selve for-løkka kan se slik ut: S_xm=0; for j = 1:m S_xm=S_xm+((-1)^(j-1)*(x.^(2*(j-1)+1))/factorial(2*(j-1)+1)); S_xm vil etter denne løkka være et array du kan plotte. factorial er Matlabfunksjonen for fakultet. Løsningsforslag: Følge kode løser problemet: x = linspace(0,2*pi,1000); m = 10; S_xm = 0; for i = 1:m S_xm=S_xm+((-1)^(i-1)*(x.^(2*(i-1)+1))/factorial(2*(i-1)+1)); c. Lag en figur der du plotter sin(x) og S m (x). Ha ulik farge på de to grafene. Start med m = 1 og lag nye figurer for forskjellige m-verdier mellom 1 og 10. Forklar hva du ser. Hint: det kan være lurt å angi verdiene for y-aksen: ylim([min(s) max(s)]), der S=sin(x) fra a.. Løsningsforslag: Følge kode løser problemet: x = linspace(0,2*pi,1000); m = 10; S_xm = 0; for i = 0:m S_xm = S_xm+((-1)^(i)*(x.^(2*(i)+1))/factorial(2*(i)+1)); S = sin(x); plot(s); hold on; plot(s_xm, r ); ylim([min(s) max(s)]); Vi ser her at når m >= 10 så har vi en sammenfalle kurve med sin(x). 111
112 177. Kandidatene 1 til 10 har fått følge poengsum på eksamen: 51, 42, 70, 99, 65, 12, 78, 67, 33 og 90. Lag et program som skriver ut, med en linje per kandidat, kandidatnummer og hvor mange poeng kandidaten har fått. png=[ ]; %poeng per kandidat n=length(png); for j=1:n fprintf( Kandidat %i har fâtt %i poeng,j,png(j)) Legg merke til at vi bruker indeksvariabelen j både til kandidatnummer og som indeks I denne oppgaven skal vi se mer på hvordan vi kan aksessere tegnene i en strengvariabel. a. Lag en strengvariabel az som inneholder alle bokstavene i alfabetet. az= abcdefghijklmnopqrstuvwxyz ; b. Hva blir H når: H(1)=az(8), H(2)= az(5), og H(3)= az(9)? Løsningsforslag: hei c. Skriv navnet ditt ved å trekke ut de riktige bokstavene fra az Hint: Trenger du mellomrom kan du legge til dette på slutten av alfabetet. disp([az(1),az(4),az(1)]) d. Bruk en løkke til å lage strengvariabelen za, som er alfabetet baklengs. n=length(az) for i=1:n za(i)=az(n+1-i); 112
113 179. gitt løkka: m=0; for i=1:10 m=m+i; a. Bruk sprintf til å skrive ut verdien til m for hvert steg i løkka sammen med hvilket steg det er i løkka Løsningsforslag: m=0; for i=1:10 m=m+i; fprintf( verdien av m er %d og det er gâtt %d iterasjoner.,m,i) b. La m starte på 0.5, og gjenta det samme, slik at m får to desimaler. Løsningsforslag: m=0.5; fprintf( verdien av m er %.2f og det er gâtt %d iterasjoner.,m,i) 180. Gitt strengvariabelen tall = ( u2 liv3 4ever ). a. Bruk str2num til å legge sammen tallene i denne teksten. Løsningsforslag: a=str2num(tall(2))+str2num(tall(7))+str2num(tall(9)) b. Hva får du om du ikke bruker str2num? 181. Gitt strengvariablene dato1 = ; dato2 = ; dato3 = 5/01/2008 ; a. Bruk num2str, str2num og fprintf til å skrive ut disse datoene på formen Denne datoen er fra året yyyy og dagen er dd i mm 113
114 b. Vanskelig: istedenfor tallet til måneden, skriv forkortelsen på tre bokstaver til den aktuelle måneden, som jan, feb, mar, osv. Denne datoen er fra året yyyy og dagen er dd.mnd dato1 = ; dato2 = ( ); dato3 = ( 5/01/2008 ); dato = num2str(dato1); mnd1=str2num(dato(5:6)); dag1=str2num(dato(7:8)); aar1=str2num(dato(1:4)); fprintf( Denne datoen er fra Âret %d og dagen er %d i %2.d,aar1,dag1,mnd1) dag2=str2num(dato2(6:7)); mnd2=str2num(dato2(9:10)); aar2=str2num(dato2(1:4)); fprintf( Denne datoen er fra Âret %d og dagen er %d i %2.d,aar2,dag2,mnd2) dag=str2num(dato3(1)); mnd=str2num(dato3(3:4)); aar=str2num(dato3(6:9)); fprintf( Denne datoen er fra Âret %d og dagen er %d i %2.d,aar,dag,mnd) if mnd == 1 mnd= jan ; elseif mnd == 2 mnd = feb ; elseif mnd == 3; mnd = mar ; %osv fprintf( Denne datoen er fra Âret %d og dagen er %d.%s,aar,dag,mnd) 182. Skriv inn matrisene A =
115 og og gjennomfør operasjonene C=[A,B] C(2,4) C(:,[2 3]) C([1 3],3:5) B = For å få noe ut av oppgaven bø den gjøres først uten å bruke Matlab. Løsningsforslag: Svarene er: C = C(2,4) = 4 C(:,[2 3]) = C([1 3],3:5) = Undersøk hva kommandoen» [A;B] gjør når A og B er to matriser På begynnelsen av denne seksjonen har du fått oppgitt temperaturutviklingen på 4 målestasjoner. a. Regn ut temperaturforskjellene mellom stasjon 4 og stasjon 1 på alle dagene. b. Plott temperatur som en funksjon av tid på de fire målestasjonene i samme figur. Sett navn på begge aksene på figuren. T=[ ; ; 115
116 ; ] t1=t(1,:) t2=t(2,:) t3=t(3,:) t4=t(4,:) figure hold on plot(t1, r ) plot(t2, g ) plot(t3, k ) plot(t4, b ) xlabel( dag nummer ) ylabel( temperatur i Celsius grader ) 185. Gitt matrisen T=[ ; ] Matrisen T inneholder temperaturer fra 2 målestasjoner. Det er tatt en temperaturmåling pr. dag. Skriv matrisen inn i Matlab. Plott temperaturene fra de to stasjonene i samme figur, og bruk ulike farger på kurvene. Sett navn på aksene. La x-aksen gå fra 1 til 12. Lag stjerner i grønt som angir der temperaturen er lik null i figuren. Løsningsforslag: Følge kode løser problement: T = [ ; ]; x = 1:12; plot(x,t(1,:)); hold on plot(x,t(2,:), r ); plot(x,0, g* ); xlabel( Tid ); ylabel( Temperatur ); 186. Gitt matrisen A = [ ; ] B= [10 11; 12 13] 116
117 a. Hvor mange rader/kolonner har A og B? Løsningsforslag: A har to rader og fire kolonner. B har to rader og to kolonner. b. Hvor mange rader/kolonner har C = [A, B]? Løsningsforslag: C = [A,B] har to rder og seks kolonner. c. Hvilken rad i C er lengst? Løsningsforslag: Radene i C er like lange. d. D = [C (:, 3 : 4)] Hvor mange rader/kolonner har D? Løsningsforslag: D har to rader og to kolonner Gitt matrisen P = [1 2; 3 4; 5 6; 7 8] Q= [10; 11; 12; 13] a. Hvor mange rader/kolonner har P og Q? Løsningsforslag: P har 4 rader og 2 kolonner. Q har 4 rader og 1 kolonne. b. Hvor mange rader/kolonner har R = [P,Q]? Løsningsforslag: R = [P,Q] har 4 rader og 3 kolonner. c. Hva blir P(1,2) +Q(2,1) Q(4,1)? Hvilke tall inngikk i regnestykket? Løsningsforslag: P(1,2) -> 2, Q(2,1) -> 11, Q(4,1) -> 13 så vi får som blir 0. d. Lag arrayer av hver kolonne i R. Løsningsforslag: Følge kode løser problement: Rc1 = R(:,1); Rc2 = R(:,2); Rc3 = R(:,3); e. Lag arrayer av hver rad i R. Løsningsforslag: Følge kode løser problement: Rr1 = R(1,:); Rr2 = R(2,:); Rr3 = R(3,:); Rr4 = R(4,:); 117
118 f. Vanskelig: Klarer du ved hjelp av disse arrayene å lage matrisene Z = P og Y = Q? Løsningsforslag: Z=[Rc1,Rc2]; Y=Rc3; 188. Lag en matrise der første kolonne inneholder temperaturene fra 0 til 40 grader i Celsius, andre kolonne inneholder de tilsvare temperaturer i Fahrenheit, og tredje kolonne inneholder tilsvare temperaturer i Kelvin. Sammenhengen mellom Celsius(C) og Fahrenheit(F) er F = 1.8C + 32, og mellom Celsius (C) og Kelvin (K) K = C + 273,15. Nb: Gjør dette ved å programmere, ikke skriv inn alle verdiene for hånd! T=0:40; F=(T*1.8)+32; K=T-273; t=[t; F; K]; t eller T = zeros(41,3); T(:,1) = 0:40; T(:,2) = T(:,1).* ; T(:,3) = T(:,1) ; 189. Lag en matrise med 5 rader og 5 kolonner der tallet i hvert punkt er gitt ved radnr*kolonnenr. Løsningsforslag: Følge kode løser problement: M = zeros(5,5); for j = 1:5 for i = 1:5 M(i,j) = i*j; 190. Vi definerer matrisen M =
119 a. Legg inn matrisen i Matlab. Løsningsforslag: M = [ ; 0 1 2; 1 2 3]; b. Lag matrisen N som har radene til M som kolonner og kolonnene til M som rader. Løsningsforslag: N = M ; c. Gir N(1:2, 2:3) og M(1:2, 2:3) det samme svaret? Løsningsforslag: Nei siden matrise N er den transponerte av matrise M. d. Gir N(1,1) og M(1:1,2:3) det samme svaret? Løsningsforslag: Nei siden vi bruker bare et element fra N og to elementer fra M. 191 (Flervalgsoppgave, kun ett riktig svar). For å få noe ut av oppgaven bør den gjøres uten å bruke Matlab. Hvilket av følge utsagn er sanne? Art = [1 1.2; 2.1 2; 7 8.9] Gir feilmelding siden dimensjonene ikke stemmer Ar t = ( ) Ar t = Ar t(1 : 3) = 7 Løsningsforslag: Det andre alternativet er riktig. 192 (Flervalgsoppgave, kun ett riktig svar). Hvilket av følge utsagn er sanne? En matrise kan ikke ha forskjellig antall rader og kolonner. Antall rader i en matrise varierer med hvilken kolonne du er i. Matriser brukes sjelden av proffe programmerere siden du mister kontrollen over data. Matriser kan ha mange flere enn 3 dimensjoner. Løsningsforslag: Det fjerde alternativet er riktig. 119
120 193. Gitt matrisen T=[ ; ] Matrisen T inneholder temperaturer fra 2 målestasjoner over 12 dager. a. Lag et array av hver rad i matrisen. b. Legg til en tredje målestasjon med målingene slik at T nå har 3 rader. c. Finn temperaturene på dag 7. d. Lag en matrise som kun inneholder en ukes observasjoner som starter på dag 3 e. Lagre arbeidet ditt i en m fil eller diary. : T=[ ; ]; T1=T(1,:); %a T2=T(2,:); T3=[ ]; %b T=[T;T3]; Tdag7=T(:,7); %c Tuke=T(:,3:9); %d 194. Opprett arrayen» G=linspace(0,10,100); a. Hva blir summen av denne? b. Hvor lang er denne arrayen? c. Del arrayen opp i to arrayer, E og F, der E inneholder den første halvdelen av G, og F den andre halvdelen. d. Hva blir gjennomsnittet av F E? 120
121 G=linspace(0,10,100); sum(g) length(g) E=G(1:50); F=G(51:100); H=F-E; mean(h) hvor svarene er 500 og 100 for a) og b) 195. På begynnelsen av seksjonen om matriser har du fått oppgitt temperaturutvikling i 7 dager fra 4 stasjoner som ligger i samme område. a. Lag en figur over temperaturen som en funksjon av tid ved de 4 stasjonene. figure(1) plot(t(:,1)) hold on plot(t(:,2), r ) plot(t(:,3), k ) plot(t(:,4), g ) leg( st.1, st.2, st.3, st.4 ) title( Temperatur for fire stasjoner ); xlabel( Tid ); ylabel( Temperatur ) b. Beregn den gjennomsnittlige temperaturen for hver dag i dette området. Beregn også standardavviket. Bruk figuren fra a. for å kontrollere om verdiene du får her virker korrekte. Tmean = mean(t); disp(tmean) Tstd = std(t); disp(tstd) 196. Legg vannførselen for elvene fra tabellen nedenfor inn i en vektor med navn Vann. 121
122 Tabell 1: Verdens 12 største elver etter vannførsel [m 3 /s]: # Navn Vannførsel [m 3 /s] lengde [km] 1) Amazonas ) Congo ) Ganges ) Orinoco ) Yangtze ) Rio Negro ) Parana ) Yenisei ) Lena ) Madeira ) Mississipi ) Mekong a. Beregn kun ved hjelp av arrayoperasjoner: 1. Total vannførsel. 2. Gjennomsnittslig vannførsel for elvene. 3. gjennomsnittet og summen av vannførselen dersom vi ikke regner med Amazonas. 4. Siden Madeira renner ut i Amazonas ønsker vi også å beregne uten denne. Hva blir nå total vannmengde (inkl. Amazonas)? 5. VANSKELIG: Hva blir snittet uten Madeira (inkl.amazonas)? Legg så lengdene til elvene inn i en vektor ved navn Lengde. b. Hvor lange er elvene til sammen? c. Gjør følge: 1. Gang elvens lengde [km] med dens vannførsel og lagre resultatet i et array Vannlengde 2. Hva blir gjennomsnittet til Vannlengde? 3. Hvilken elv er minst ved denne måten å se det på? -og hvor stor er den? 122
123 Løsningsforslag: Svarene er Vann= [ ]; 1.a) sum(vann) = [m^3/s] 1.b) mean(vann) = [m^3/s] 1.c) sum(vann(2:12)) = [m^3/s] mean(vann(2:12))= [m^3/s] 1.d) sum(vann(1:9))+sum(vann(11:12))= e) Feks: (sum(vann(1:9))+sum(vann(11:12)))/(length(vann)-1)= Lengde =[ ]; 2. sum(lengde) = a) Vann.*Lengde 3.b) mean(vannlengde)= *10^8 3.c) min(vannlengde)= *10^ Befolkningstallene nedenforer hentet fra Wikipedia i April Tabell 2: Land med høyest befolkning # Land Befolkning % av verdens befolkning 1) Kina 1,337,030, % 2) India 1,179,744, % 3) USA 309,034, % 4) Indonesia 231,369, % 5) Brasil 192,801, % 6) Pakistan 169,274, % 7) Bangladesh 162,221, % 8) Nigeria 154,729, % 9) Russland 141,927, % 10) Japan 127,380, % 11) Mexico 107,550, % 12) Filippinene 92,226, % På samme tidspunkt var verdens befolkning totalt milliarder. Legg tallene over befolkningen i de 12 landene inn i et array som du kaller populasjon. 123
124 clear all close all befolkning=[ ]; prosent= [ ]; land=char( Kina, India, USA, Indonesia, Brasil, Pakistan,... Bangladesh, Nigeria, Russland, Japan, Mexico, Filippinene ); %oppg a bar(befolkning) set(gca, XTickLabel,land); ylabel( Befolkning ) title( De 12 mest befolkede landene i verden ) %oppg b summen = sum(befolkning); %oppg c snitt=mean(befolkning); avvik=std(befolkning); %oppg d andel =sum(prosent); %oppg e norge= ; del_12=norge/snitt; %oppg f verden = 6.816*1e9; del_verden=norge/verden; %oppg g befolkning2=befolkning(3:length(befolkning)); prosent2= prosent(3:length(prosent)); summen = sum(befolkning2); snitt=mean(befolkning2); avvik=std(befolkning2); andel =sum(prosent2); del_12=norge/snitt; a. Lag et søylediagram over befolkningen i de 12 landene. b. Finn summen av befolkningen i de 12 landene. Løsningsforslag:
125 c. Finn gjennomsnittet og standardavviket. Løsningsforslag: Gjennomsnitt: , standardavvik: d. Hvor stor del av jordas befolkning bor i de 12 mest befolkede landene? Løsningsforslag: 61.71% e. Pr. 1. Januar 2010 var befolkningen i Norge 4,858,200. Hvor mange prosent er dette i forhold til gjennomsnittet du fant i c.? Løsningsforslag: 0.014% f. Hvor mange prosent er Norges befolkning av jordas befolkning? Løsningsforslag: % g. Kina og India har stor innvirkning på tallene du får siden det bor så mange her. Gjør oppgave b.-e. en gang til uten tallene for Kina og India, og se om du får et veldig ulikt resultat. Løsningsforslag: Vi får nå svarene b c Gjennomsnitt: , standardavvik: d 24.78% e % 198. Finn, uten å programmere, om det siste uttrykket er sant eller ikke. a=2; b=2*a; c=45; d=c-10*b; a<d & (b>c d<c) & ~(a==b) Kontroller med Matlab om du har riktig svar. Løsningsforslag: Hvordan man går fram: Regne ut verdiene: a=2 b=4 c=45 d=5 Sammenligne og kombinere sammenlignigene: 125
126 1.: a<d: sant 2.: b>c ikke sant; 3.: d<c sant; 4.: derfor blir 2. eller 3. sant 5.: a ulik b sant 6.: baade 1. og 4. og 5. er sant; derfor er det totale sant Skriv i en enklere form følge test: if ~(a>b) og test med noen verdier av a og b. if a<=b 200. Funksjonen arcsin(a) er definert bare hvis verdien til a er mellom -1 og 1. Lag et program som tester verdien av a, tar arcsin hvis mulig, eller skriver ut en melding hvis det ikke går an å ta arcsin av a. if (abs(a)>1) disp ( arcsin kan ikke regnes ut for denne a ) else b=arcsin(a) 201. La oss lage et par typer enkle if-tester. a. Lag en if-test som tester om en tallvariabel er et heltall. a= 3.000; b= ceil(a); %fix, floor, round funker ogsâ if a==b disp( heltall ) else disp( ikke heltall ) b. Lag en if-test som tester om et heltall er partall eller oddetall. 126
127 b=a/2; c=ceil(b); if a==b disp( partall ) else disp( oddetall ) c. Lag en if-test som tester hvilken variabel som er størst og deretter setter begge variablene lik hverandre. if a <=b a=b else b=a 202. For å få noe utbytte av denne oppgaven må man la være å programmere den, og heller tenke gjennom den. a=2; b=3; if (a>1 & b<3) disp( ja ) else disp( nei ) a. Hva skrives ut? Hvorfor? Løsningsforslag: nei b. Hva skrives ut om a=0 og b=5? Løsningsforslag: nei c. Hva skrives ut dersom a=1 og b=4? Løsningsforslag: nei d. Hva skrives ut dersom a=2 og b=3? Løsningsforslag: nei 127
128 203. For å få noe utbytte av denne oppgaven må man la være å programmere den, og heller tenke gjennom den. a=2; b=3; if (a>1 b<3) disp( ja ) else disp( nei ) a. Hva skrives ut? Hvorfor? Løsningsforslag: a>1 : sant; b<3 : feil, derfor feil; derfor nei. b. Hva skrives ut om a=0 og b=5? Løsningsforslag: a>1 : feil; b<3 : feil, derfor feil; derfor nei. c. Hva skrives ut dersom a=1 og b=4? Løsningsforslag: a>1 : feil; b<3 : feil, derfor feil; derfor nei. d. Hva skrives ut dersom a=2 og b=3? Løsningsforslag: a>1 : sant; b<3 : feil, derfor feil; derfor nei For å få noe utbytte av denne oppgaven må man la være å programmere den, og heller tenke gjennom den. a=1; b=3; if a>1 & b<3 disp( ja ) if a<1 & b>3 disp( hmm ) else disp( nei ) a. Hva skrives ut? Hvorfor? Løsningsforslag: nei b. Hva skrives ut om a=0 og b=5? Løsningsforslag: hmm 128
129 c. Hva skrives ut dersom a=1 og b=4? Løsningsforslag: nei d. Hva skrives ut dersom a=2 og b=2? Løsningsforslag: ja nei e. Hva skrives ut dersom a=2 og b=3? Løsningsforslag: nei f. Hvilke verdier kan a og b ha for at bare nei skal bli skrevet ut? Løsningsforslag: enten må a være lik 1 eller b lik Vi skal nå se litt på hvordan man kan bruke en if-test i en løkke. a. Lag en løkke som teller fra 1 til 100, og bruk denne løkken til å lage et array A, som inneholder verdiene 1 til 100 i stige rekkefølge. Løsningsforslag: Denne koden kan brukes: A = []; for i = 1:100 A(i) = i; b. Bruk samme løkke og en if-test til å lage et array B som inneholder alle tallene i løkka som går opp i 10. Løsningsforslag: Kode som løser problemet: B = []; j = 1; for i = 1:100 if(floor(i/10) == ceil(i/10)) B(j) = i; j = j + 1; c. Gjør om det inne i løkka slik at de tallene som er i B ikke er med i A. Hvor lange blir array A og B da? Løsningsforslag: Løsningsforslag: 129
130 A = []; B = []; j = 1; k = 1; for i = 1:100 if(floor(i/10) == ceil(i/10)) B(j) = i; j = j + 1; else A(k) = i k = k + 1; Lengdene : 10 og Kandidatene 1 til 10 har fått følge poengsum på eksamen: 51, 42, 70, 99, 65, 12, 78, 67, 33 og 90. Kandidatene står hvis de har minst 44 poeng. Lag et program som skriver ut, med en linje per kandidat, kandidatnummer og om han har stått eksamen eller ikke. png=[ ]; %poeng per kandidat grense=44; n=length(png); for i=1:n if png(i)<grense disp(sprintf( Kandidat %i har ikke bestâtt,i)) else disp(sprintf( Kandidat %i har bestâtt,i)) 207. Beregn snødybde ut fra følge meteorologiske data. Temperatur per dag i Celsius ( ) Nedbør per dag i millimeter ( ) Anta at det ikke var snø da målingene startet og at nedbør kommer som snø når 130
131 det er temperatur mindre eller lik 1 C (1 mm nedbør gir omtrent 1 cm snø). Anta videre at ingen snø smelter. Lag et søylediagram over snødybde som funksjon av tid. : temp=[ ]; ned=[ ]; snotot=0; for i=1:length(temp); if (temp(i)<=1); snotot=snotot+ned(i); sno(i)=snotot; bar(sno) ylabel sn dypte (i cm) xlabel dag 208. Gitt en serie observasjoner av jordskjelv ved deres seismiske energi. Richter=[5.5, 5.3, 2.9, 3.6, 4.1, 5.2, 3.7, 4.4, 6.9, 5.8, 4.0]; Richters skala beskriver energien i et jordskjelv. a. Bruk en if-test til å legge disse jordskjelvene inn i 3 kategorier Lett skjelv ML <= 4 Medium skjelv 4 < ML < 5.5 Alvorlig skjelv M L >= 5.5 Løsningsforslag: Denne koden løser problemet: Ls = 0; Ms = 0; Ks = 0; for i = 1:length(Richter) if(richter(i) <= 4) Ls = Ls + 1; if(richter(i) > 4 & Richter(i) < 5.5) Ms = Ms + 1; if(richter(i) >= 5.5) 131
132 Ks = Ks + 1; b. Skriv til skjerm hver gang det er et medium eller kraftig skjelv, og hvor mange slike skjelv det har vært tidligere. Løsningsforslag: Kode som løser problemet Ls = 0; Ms = 0; Ks = 0; for i = 1:length(Richter) if(richter(i) <= 4) disp([ Et lett jordskjelv med styrke,num2str(richter(i))]); disp([ Det har vêrt,num2str(ls), slike skjelv tidligere ]); Ls = Ls + 1; disp( ) if(richter(i) > 4 & Richter(i) < 5.5) disp([ Et medium jordskjelv med styrke,num2str(richter(i))]); disp([ Det har vêrt,num2str(ms), slike skjelv tidligere ]); disp( ) Ms = Ms + 1; if(richter(i) >= 5.5) disp([ Et kraftig jordskjelv med styrke,num2str(richter(i))]); disp([ Det har vêrt,num2str(ks), slike skjelv tidligere ]); disp( ) Ks = Ks + 1; c. Forskjellen i energi mellom to skjelv kan beskrives ved E = (m 1 m 2 ) Hvor mange ganger mer energi er det i det største skjelvet i serien enn i det minste? Løsningsforslag: Kode som løser problemet minste = min(richter); meste = max(richter); forskjell = exp((2/3)*(meste - minste)); 132
133 Det er 14.4 ganger mer energi i det st rste i forhold til det minste Lage matriser ved hjelp av to for-løkker. a. Lag en 2 6-matrise M der verdien i hvert punkt er gitt av radnr. M=zeros(2,6); for j=1:6 for 1=1:2 M(i,j)= i; b. Lag en 6 2-matrise N der verdien i hvert punkt er gitt av kolonnenr i samme for-løkker som i a. M=zeros(2,6); N=zeros(6,2); for j=1:6 for 1=1:2 M(i,j)= i; N(j,i)= j; c. Lag en 5 3-matrise P der tallet i hvert punkt er gitt ved radnr*kolonnenr ved å bruke to for-løkker. P=zeros(5,3); for i=1:5 for j=1:5 P(j,i)= j*i; d (vanskelig). Lag matrisene fra a., b. og c. samtidig ved å bruke kun to for-løkker. Hint: bruk if-tester. 133
134 M=zeros(2,6); N=zeros(6,2); P=zeros(5,3); for i=1:6 for j=1:6 if j<3 M(j,i)= j; if i<3 N(i,j)= i; if j<6 & i<6 P(j,i)= j*i; 210. La oss igjen se på partall og oddetall. a. Lag en while-løkke som setter de n første oddetallene i et array. Sett n lik et tall i begynnelsen av programmet og lag så en while-løkke der du lager et array med n oddetall. n=10; odde=zeros(1,n); odde(1)=1; i=2; while i <= n odde(i)= odde(i-1)+2; i=i+1; b. Gjør om på programmet fra a. slik at while-løkken nå lager de n første partallene. n=10; par=zeros(1,n); 134
135 par(1)=2; i=2; while i <= n par(i)= par(i-1)+2; i=i+1; c. Bruk en for-løkke til å programmere de n første kvadrattallene. Legg tallene i et arrray som du kaller kvadrat. n=10; kvadrat = zeros(1,n); for i = 1:n kvadrat(i)=i^2; d. Bruk så en while-løkke til å løse c. Kall arrayet kvadrat2. Er kvadrat og kvadrat2 like? (Hvis ikke har du gjort noe feil;) n=10; kvadrat2 = zeros(1,n); i=1; while i <= n kvadrat2(i)=i^2; i=i+1; 211. I denne oppgaven skal vi lage arrayer fra noen mye brukte rekker. a. Bruk en løkke, for eller while, til å beregne M for M lik 100, 1000 og 10000? Løsningsforslag: Denne koden løser problemet: S = zeros(1,3); M = [100, 1000, 10000]; 135 i=1 1 i. Hva blir summen
136 for j = 1:length(M) S = 0; for i = 1:M(j) S(j) = S(j) + 1/i; disp([ For M =,num2str(m(j)), er summen, num2str(s(j))]); For M = 100 er summen For M = 1000 er summen For M = er summen i 2 for de samme M-verdiene. Hva er forskjellen fra sum- b. Beregn så M men i a.? i=1 Løsningsforslag: Denne koden løser problemet: S = zeros(1,3); M = [100, 1000, 10000]; for j = 1:length(M) S = 0; for i = 1:M(j) S(j) = S(j) + 1/i^2; disp([ For M =,num2str(m(j)), er summen, num2str(s(j))]); figure hold on plot (S) plot (S2) hold off For M = 100 er summen For M = 1000 er summen For M = er summen Om du vil kan du lage arrayer av de to rekkene i a. og b., og så plotte resultatet. Da ser du godt forskjellen Sett alle verdiene til matrisen gitt på begynnelsen av Kapittel?? i en fil som du kaller temp.dat, og les den inn i Matlab. Pass på at du ikke har noen andre tegn enn tallene og mellomrom i fila. Altså ingen semikolon, parenteser osv. 136
137 213. Les inn dataene fra fila glomma.dat (denne er i GEO1040-format). Løsningsforslag: Her må vi bruke read_1040 funksjonen for å laste inn verdiene fra glomma.dat. [H M] = read_1040( glomma.dat,3, ); der det første argumentet er filnavnet, det neste er antall headerlinjer og det siste er separatoren som i dette tilfellet er mellomrom les inn filene fil1.dat, fil2.dat, og fil3.dat som tre variable fil1, fil2, og fil3. a. Hvor mange rader har henholdsvis fil1, fil2, og fil3? Løsningsforslag: fil1:4, fil2:16, fil3:4 b. Hvor mange kolonner har henholdsvis fil1, fil2, og fil3? Løsningsforslag: fil1:18, fil2:1, fil3:4 c. Hvor mange tall er det i hver av de tre filene? Løsningsforslag: fil1.dat: 4x18, fil2.dat: 16x1, fil3.dat: 4x4 d. Legg radene i fil1 inn i arrayer. rad1=fil1(1,:),rad2=fil1(2,:),rad3=fil1(3,:),rad4=fil1(4,:) e. Legg kolonnene i fil3 inn i arrayer. kolonne1=fil3(:,1),kolonne2=fil3(:,2),kolonne3=fil3(:,3),kolonne4=fil3(:,4) f. Finn summen av kolonnene i fil3. sum1=sum(rad1)=69, osv g. Finn summen av radene i fil1. sum1=sum(kolonne1)=242, osv. h. Finn summen av alle tallene i fil2. 137
138 sum(fil2)=185 i. Hva er gjennomsnittet av kolonnene i fil1? snitt1=mean(fil1(:,1))=2.5, osv j. Hva er gjennomsnittet av radene i fil3? snitt1=mean(fil3(1,:))=1423.2, osv. k. Hva er gjennomsnittet av fil2? snitt=mean(fil2)=11.56 l. Hva er summen av alle tallene i de tre filene til sammen? sum(sum(fil1))+sum(fil2)+sum(sum(fil3))=11827 m. Hva er gjennomsnittet av alle tallene i de tre filene til sammen? mean(mean(mean(fil1))+mean(fil2)+mean(mean(fil3)))= Les inn filen temp.dat. Lag en figur der du plotter temperatur, og en linje som markerer null grader. Sett navn på aksene og en tittel på grafen. load temp.dat plot(temp) hold on plot(1:length(temp),0, g ) xlabel( dager ) ylabel( grader ) title( Temperaturdata ) 138
139 216. Filen TempNedborVind.dat inneholder temperatur-, nedbør- og vinddata for ett år. De 365 plassene inneholder temperaturer i Celsius, de neste 365 plassene inneholder nedbør i mm og de siste 365 plassene inneholder vindstyrke gitt i m/s. Du skal lese inn filen og lage tre arrayer, med henholdsvis temperatur, nedbør, og vind. Lag så tre figurer der du plotter arrayene. Husk navn på akser og tittel. load TempNedborVind.dat temperatur=tempnedborvind(1:365); nedbor=tempnedborvind(365:730); vind=tempnedborvind(730:1095); subplot(1,3,1) plot(temperatur) xlabel( dager ) ylabel( grader [C] ) title( temperatur ) subplot(1,3,2) plot(nedbor, g ) xlabel( dager ) ylabel( [mm] ) title( nedb{\o}r ) subplot(1,3,3) plot(vind, r ) xlabel( dager ) ylabel( [m/s] ) title( vind ) 217. Les inn filen dallas_temp.dat. Første kolonne inneholder måned, andre kolonne dag, tredje kolonne år, og siste kolonne temperatur i Fahrenheit. a. Les inn de fire kolonnene og legg dem i fire forskjellige arrayer som du kaller mnd, dag, aar, og temp. load dallas_temp.dat mnd = dallas_temp(:,1); dag = dallas_temp(:,2); aar=dallas_temp(:,3); temp = dallas_temp(:,4); 139
140 b. Gjør om temperaturene i temp fra Fahrenheit til Celsius ved hjelp av formelen C = (F 32)/1.8. Kall den nye temperaturarrayen temp2. for i = 1:length(temp) temp2(i)=(temp(i)-32)/1.8; c. Lag en figur der du plotter temp2. Lag en linje i samme figur som markerer null grader. Sett navn på akser, og en tittel på figuren. plot(temp2) hold on plot(1:length(temp2),0, g ) d. To steder ser du målefeil. Der er temperaturen lik 99 Fahrenheit, eller Celsius. Lag en løkke der du løper gjennom temp, tester om temperaturen er 99F, og om den er det erstatter du temperaturen med temperaturen fra dagen før. Gjør så b. og c. om igjen. Hint: Det er mye lettere å gjøre dette med temp enn med temp2, siden temp har eksakt 99F som verdi for målefeil. for i = 1:length(temp) if temp(i)==-99 temp(i)=temp(i-1); for i = 1:length(temp) temp2(i)=(temp(i)-32)/1.8; plot(temp2) 218. Tegn grafene til disse funksjonene: f (x, y) = x 2 y 2, g (x, y) = sin x y 2 +x 2, h(x, y) = sin(e x+y ) for x mellom 0 og 2 og y mellom 1 og 2. Finn selv hvilken inndeling av aksene som trengs for at alle funksjonene skal være bra representert. Vri på flatene for å få et best mulig inntrykk. 140
141 Løsningsforslag: Vi prøver forskjellige inndelinger. Funksjonen h trenger at x- og y-aksene er findelt for at grafen skal kunne se bra ut. X = 0:0.01:2; Y = 1:0.01:2; [x,y]=meshgrid(x,y); f = x.^2.* y.^2; g = (sin(x)./y.^2) + x.^2; h = sin(exp(x+y)); figure(1) mesh(x,y,f) title( funksjon f ) xlabel( x ) ylabel( y ) zlabel( f ) figure(2) mesh(x,y,g) title( funksjon g ) xlabel( x ) ylabel( y ) zlabel( g ) figure(3) mesh(x,y,h) title( funksjon h ) xlabel( x ) ylabel( y ) zlabel( h ) 219. Tegn kurvene r 1 (t) = (t, t 2,sin t) og r 2 (t) = (sin 2 t,cos 2 t,e t ) for t fra 0 til 10π. Velg selv inndeling av t-intervallet. Vri på koordinatsystemet for å se kurvene best mulig. Løsningsforslag: Mulig kode: t = linspace(0,10*pi,100); figure(1) plot3(t,t.^2, sin(t)) xlabel( t ) ylabel( t squared ) zlabel( sin(t) ) figure(2) plot3(sin(t).^2, cos(t).^2,exp(-t)) 141
142 xlabel( sin(t) squared ) ylabel( cos(t) squared ) zlabel( exp(-t) ) 220. Bruk kommandoen plot3 til å lage en tredimensjonal strektegning av en terning Tegn grafen til funksjonen s(x, y) = sin(πx) sin(πy). La x=y=linspace(0,4,n). Varier antall punkter, n, for å se hvordan dette rer flaten. Løsningsforslag: Mulig kode for eggboks funksjonen: n=100; x=linspace(0,4,n); y=linspace(0,4,n); [X,Y]=meshgrid(x,y); s = sin(pi*x).*sin(pi*y); figure mesh(x,y,s) title( funksjon sin*sin ) xlabel( x ) ylabel( y ) zlabel( s ) 222. Lag en funksjon som returner minimumsverdien i en 3 3-matrise. function [amin]=minmat3(a) b=min(a); c=min(b); amin=min(c); eller function [amin]=minmat3(a) amin=min(min(min(a))); 223. Lag en funksjon som returner både gjennomsnitt og standardavvik av verdiene i et array. Sjekk at dine resultater er riktig ved hjelp av de to innebygde funksjonene mean(x) og std(x), men ikke bruk dem i din egen funksjon. function [g,s]=gjennom(a) n=length(a) 142
143 temp=0; for i=1:n temp=temp+a(i); g=temp/n temp=0; for i=1:n temp=temp+(a(i)-g)^2; s=sqrt(temp/(n-1)) 224. Lag en funksjon som regner ut leddene i følgen {x n } gitt ved: x n+2 = ax n+1 + bx n x 1 = c, x 2 = d Filen skal ha inn-parametre a, b, c, d, m, og skal returnere de m første verdiene i følgen. x_1=c; x_2=d s=folge(a,b,c,d,m) function s=folge(a,b,c,d,m) s(1)=c; if (m==1); return; ; s(2)=d; if (m==2); return; ; for i=3:m s(i)=a*s(i-2)+b*s(i-1); 225. Lag en funksjon som regner ut leddene i følgen {x n } gitt ved: x n+1 = ax n (1 x n ) x 1 = b Funksjonen skal ha inn-parametre a,b,m, og skal returnere de m første verdiene i følgen. Sett m = 100, se på tilfellene b = 0.2 og b = 0.8, og kjør programmet for hhv. a = 1.5, a = 2.8, a = 3, a = 3.1, a = 3.5, a = 3.9. Plott resultatene. Eksperimenter videre hvis du har lyst, men behold humøret selv om du ikke finner noe mønster; fenomenet du ser på er et av utgangspunktene for det som kalles kaos-teori! 143
144 opp3 regne ut m ledd i x_n+1 = a x_n (1-x_n) x_1=b; [s]=folgekaos(a,b,m) function [s]=folgekaos(a,b,m) s(1)=b; if (m==1); return; ; for i=2:m s(i)=a*s(i-1)*(1-s(i-1)); m=100; b=[ ]; a=[ ]; for j=1:2; for i=1:6 s=folgekaos(a(i),b(j),m); figure plot(s) 226. La oss se på flere funksjoner som har flere ut-parametre. a. Lag en funksjon som tar inn et vilkårlig array som inn-parameter, og returnerer maks, min, gjennomsnitt, og lengde. function[lengde, gjennomsnitt, maks, mini] = array_funk(arr) lengde=length(arr); gjennomsnitt=mean(arr); maks=max(arr); mini=min(arr); b. Test at funksjonen virker ved å lagre svarene som feks m, mi, gj og l for arrayer fra noen tidligere oppgaver. [l,g,m,i]=array_funk(arr) 144
145 227. La oss lage oss flere nye funksjoner. a. Lag en funksjon som tester om en tallvariabel er et heltall og returnerer svaret. function[svar]= heltall(a) a= 3.000; b= ceil(a); if a==b Svar=( heltall ) else Svar=( ikke heltall ) b. Lag en funksjon som tester om en tallvariabel er partall eller oddetall og returnerer svaret function[svar]= partall(a) b=a/2; c=ceil(b); if a==b Svar=( partall ) else Svar=( oddetall ) c. Lag en funksjon som tester hvilken av 2 variable som er størst og returnerer kun den største. function[svar]= storst(a,b) if a>b Svar=a else Svar=b 145
146 d. Lag en funksjon som tester hvilket av 2 arrayer som er lengst og returnerer det korteste. function[svar]= kortest(a,b) d=length(a) e=length(b) if d>e Svar=b else Svar=a 228. Lag en funksjon fakultet, som tar inn et heltall n, og returnerer n! = n. function[n_fakultet]=fakultet(n) n_fakultet=1; if n==0 n_fakultet=1; return; for i=1:n n_fakultet=n_fakultet*i; 229. La oss se nærmere på omregning mellom Fahrenheit og Celsius. a. Lag en funksjon som regner om fra Fahrenheit til Celsius. function[f] = celcius_fahrenheit(t) F= 32+(9/5)*T; b. og en som regner om fra Celsius til Fahrenheit. 146
147 function[c] = fahrenheit_celsius(t) C= (T-32)*(9/5); c. Lag en funksjon som tar inn en temperatur og en strengvariabel som sier hva slags temperatur det er f.eks (K,F eller C), og returnerer temperaturen i både Kelvin, Celsius og Fahrenheit. function[celsius, Fahrenheit, Kelvin] = celsius_fahrenheit_kelvin(t,enhet) if enhet== K Kelvin=T; Celsius= T ; Fahrenheit= 32+(9/5)*Celsius; return elseif enhet== C Celsius=T; Kelvin= T ; Fahrenheit=32+(9/5)*T; return elseif enhet== F Fahrenheit= T; Celsius= (T-32)*(9/5); Kelvin= Celsius ; return else disp( invalid option for enhet, must be one of C,K,F ); d. Lag funksjonen din fra c. slik at temperaturene er arrayer. Tips: Dette er en nyttig funksjon som er grei å ha lagret. function[celsius, Fahrenheit, Kelvin] = celsius_fahrenheit_kelvin(t,enhet) if enhet== K Kelvin=T; Celsius= T ; Fahrenheit= 32+(9/5).*Celsius; 147
148 return elseif enhet== C Celsius=T; Kelvin= T ; Fahrenheit=((9/5).*T)+32; return elseif enhet== F Fahrenheit= T; Celsius= (T-32).*(9/5); Kelvin= Celsius ; return else disp( invalid option for enhet, must be one of C,K,F ); 230. La oss lage oss flere funksjoner. function[toer]= to(n) toer=zeros(n,1); for i=1:n toer(i)=2^(i-1); a. I kapitlet om arrayer og løkker lagde du et array (1,2,4,8,16,...,4096). Nå skal du lage en funksjon som tar imot antall plasser du vil ha i arrayet (i dette tilfellet 13), og ser tilbake arrayet du ser over. b. Gjør om funksjonen slik at den kan ta imot enhver lengde, og slik at den ser tilbake arrayen Vi skal se på utviklingen til tre generasjoner av en dyrepopulasjon. Den første generasjonen kalles x, den midterste y og den eldste z. 40% av dyrene i generasjon x overlever til generasjon y, og 70% av dyrene i generasjon y overlever til generasjon z pr. år. Dyrene i generasjon y får gjennomsnittlig 1.5 barn hver pr. år, og dyrene i generasjon z får 1.4 barn hver pr. år. Løsningsforslag: a. og b.: function[x,y,z,b] = populasjon(x1,y1,z1,b1,t) x(1)=x1; 148
149 y(1)=y1; z(1)=z1; b(1)=b1; for i=1:t x(i+1)=1.5*y(i)+1.4*z(i)+0.5*b(i); y(i+1)=0.4*x(i); z(i+1)=0.7*y(i); b(i+1)=0.2*z(i); a. Du skal lage en funksjon som tar i mot hvor mange dyr det er i hver generasjon ved tiden t=1, og ser tilbake tre arrayer som inneholder utviklingen til hver generasjon. I tillegg skal funksjonen også ta imot hvor mange tidsskritt(år) frem i tid du vil se på. Første linje i programmet ditt skal se slik ut: function[x,y,z] = populasjon(x1,y1,z1,t) Her er x1, y1, z1, og t vanlige tall, mens x, y, og z er arrayer. b. I denne funksjonen var z den eldste generasjonen. Under studiet av denne dyrepopulasjonen fant du ut at det var en generasjon til som var a eldre enn z, nemlig generasjon b! Det var 20% av dyrene som var i generasjon z som overlevde til generasjon b, og annethvert dyr i generasjon b fikk ett barn pr. år. Gjør ringene som trengs i funksjonen for at den skal beregne utviklingen til bestanden inkludert generasjon b. Første linje i programmet ditt skal nå se slik ut: function[x,y,z,b] = populasjon(x1,y1,z1,b1,t) c. Lag en ny funksjon der du ser inn arrayene x,y,z, og b. Funksjonen skal lage et plot som viser utviklingen til populasjonene. Figuren skal ha navn på aksene, tittel og de fire grafene skal ha ulike farger. Første linje i programmet ditt skal se slik ut: function figur(x,y,z,b) 149
150 function figur(x,y,z,b) plot(x) hold on plot(y, r ) plot(z, g ) plot(b, k ) xlabel( {\aa}r ) ylabel( antall dyr ) title( Populasjon ) leg( x, y, z, b ) 232 (Vanskelig). Lotto er spillet der du vinner førstepremien hvis du har tippet de 7 tallene som blir trukket blant 34 tall. Løsningsforslag: a. og b.: function[dagens_tall, tilleggstall] =Lotto(a,n) % 1. c = randperm(n); dagens_tall = sort(c(1:a)); % 2. tilleggstall =sort(c(a+1:a+3)); a. Lag en funksjon, Lotto, som trekker ut a vilkårlige tall mellom 1 og n, og ut fra inputene returnerer et array, dagens tall, med de utvalgte tallene i stige rekkefølge. Hint: funksjonen randperm(10) trekker tallene fra 1 til 10 i tilfeldig rekkefølge. Man kan evt bruke rand og ceil, men må da passe på å ikke ha flere like tall b. Gjør om funksjonen Lotto slik at den i tillegg til å returnere dagens tall også returnerer arrayen tilleggstall der tre ekstra tall er blitt trukket ut. c. Vi skal nå lage en ny funksjon, Mulige, der vi skal se litt på vinnersjansene til rekker i lotto. Opprett funksjonen Mulige som tar inn a og n som i a., og ut fra disse returnerer antall mulige rekker funksjonen fra a. kan ha. Hint: Antall rekker for n = 10 og a = 3 er (10 9 8)/(1 2 3) = n!/((n a)!a!) = ( n ) a, evt. se oppgave fra kapitlet om løkker. 150
151 function[ant_rekker] =Mulige(a,n) teller=1; nevner=1; for i=1:a teller= teller*(n-i+1); nevner= nevner*i; ant_rekker = teller/nevner; d. I viking-lotto vinner man førstepremien ved å trekke ut 6 tall blant 46 mulige, dvs n = 46 og a = 6. Bruk funksjonen Mulige til å beregne hvor mye vanskeligere det er å vinne i viking-lotto enn i vanlig lotto. Hva hvis du trengte 7 rette der og? Løsningsforslag: t=mulige(6,46)/mulige(7,34) % 1,7 e. Lag et program som kaller funksjonen Mulige, og plotter mulige utfall for forskjellige verdier av antall rette man må ha for å vinne for hhv. lotto og viking-lotto. Hvor mange rette er det vanskeligst å få i de to spillene? n=34; nv=46; for i=1:n lotto(i)=mulige(i,n); for i=1:nv vlotto(i)=mulige(i,nv); lotto=lotto/max(lotto); vlotto=vlotto/max(vlotto); plot(lotto, k ) hold on; plot(vlotto, b ) 151
152 f (Vanskelig). Lag et program som ser inn dine lotto-rekker, og som trekker ut en Lottorekke og gir deg antall riktige i din rekke. Hvor mange rette klarer du? (ignorer tilleggstall). Hint: Du kan bruke funksjonen Lotto til å lage rekkene dine. Denne oppgaven trenger god kjennskap til for-løkker. n=34; % antall tall m=5; % antall innleverte rekker a=7; % antall tall per rekke % genererer mine rekker for i=1:m mine_rekker(i,:)=lotto(a,n); % trekker vinnertallene: [vinnertall, tilleggstall]=lotto(a,n); rette_tall=zeros(1,m); for i=1:m for j=1:a tall=vinnertall(j); for k=1:a if tall==mine_rekker(i,k) rette_tall(i)=rette_tall(i)+1; vinnertall; mine_rekker; rette_tall 233. koden er a=1:10; sum=0; for k=1:11 152
153 sum=sum+a(k); 234. koden er function fak=fakultet(n) fak=n*fakultet(n-1); 235. koden er A=[1 2 3; 4 5 6]; B=[1 2; 3 4]; A*B 236. Dette programmet lager et array med n oddetall: n=10; odde=zeros(1,n); odde(1)=1; i=2; while i <= n odde= odde(i-1)+2; i=i+1; 237. Plot de to funksjonene f (x) = e 0.5x2 og h(x) = e (x 3t)2 : f=exp(-0.5*x.^2); t=0.5; h_xt=exp(-(x-3*t).^2); figure(1) plot(f) hold on plot(h_xt, g ) 238. Vi skal se på utviklingen av tre generasjoner av en dyrepopulasjon. Vi skal lage en funksjon som tar som inn-parametre hvor mange dyr det er i hver generasjon ved tiden t = 1, og returnerer tre arrayer som inneholder utviklingen til hver generasjon: function[x,y,z] = populasjon(x1,y1) x(1)=x1; 153
154 y(1)=y1; z(1)=z1; % ser pâ 100 Âr frem i tid: for n=1:100 x(t+1)=1.5*y(t)+1.4*z(t); y(t+1)=0.4*x(t); z(t+1)=0.7*y(t); 239. Denne funksjonen tar imot 3 arrayer og plotter dem: function figur(x,y,z) plot(x) hold on plot(y, r ) plot(z, g ) plot(b, k ) leg( x, y, z, b ) 240. Funksjonen variabler tar som inn-parametre a, b, og antall elementer, N, som arrayene skal inneholde. Funksjonen ser tilbake to arrayer x og y. function [a,b,n]= variabler(x,y) x = linspace(0,a,n); y = linspace(0,b,n); 241. Jeg har en fil T.dat som inneholder måledata fra 4 stasjoner med en måling pr. dag i tre mnd(jan,feb,mars). size(t)= 4 90 Jeg har en tilsvare fil, P.dat, med nedbørsdata fra de samme stasjonene og de samme tidspunktene. size(p)= 4 90 Jeg antar at det faller snø hvis temperaturen er lik eller under null. Jeg skal lage et program som beregner snødybden for de 4 stedene jeg antar at snøen blir ligge om temperaturen er under eller lik null, og at alt smelter om temperaturen er over null Virker dette programmet? Hvis ikke, hva gjør jeg feil? load P.dat; load T.dat; sno0=0; for j=1:4 for i=1:90 154
155 if T(i)<=0 snodybde(j,i)=p(i)+sno0; sno0=snodybde; else snodybde(j,i)=0; sno0=0; plot(snodybde, r ) load T.dat; load P.dat; sno0=0; for j=1:4 for i=1:90 if T(j,i)<=0 snodybde(j,i)=p(j,i)+sno0; sno0=snodybde(j,i); else snodybde(j,i)=0; sno0=0; plot(snodybde(1,:), r ) hold on plot(snodybde(2,:), g ) plot(snodybde(3,:), b ) plot(snodybde(4,:), k ) 242. Formulate an algorithm for adding two three-digit numbers. You may assume that it is known how to sum one-digit numbers. Svar: We represent the three-digit numbers by their decimal numerals which are integers in the range 0 9. The numerals of the number x = 431 for example, 155
156 is represented by x 1 = 1, x 2 = 3 and x 3 = 4. Adding two arbitrary such numbers x and y produces a sum z which can be computed by the algorithm if x 1 + y 1 < 10 z 1 := x 1 + y 1 ; else x 2 := x 2 + 1; z 1 := x 1 + y 1 10; if x 2 + y 2 < 10 z 2 := x 2 + y 2 ; else x 3 := x 3 + 1; z 2 := x 2 + y 2 10; if x 3 + y 3 < 10 z 3 := x 3 + y 3 ; else z 4 := 1; z 3 := x 3 + y 3 10; 243. Formulate an algorithm which describes how you multiply together two three-digit numbers. You may assume that it is known how to add numbers. Svar: We use the same representation as in the solution for exercise 242. Multiplication of two three-digit numbers x and y can then be performed by the formulas pr oduct1 := x 1 y x 1 y x 1 y 3 ; pr oduct2 := 10 x 2 y x 2 y x 2 y 3 ; pr oduct3 := 100 x 3 y x 3 y x 3 y 3 ; pr oduct := pr oduct1 + pr oduct2 + pr oduct3; 244. Use a truth table to prove that the exclusive or operator is associative, i.e., show that if p, q and r are logical operators then (p q) q = p (q r ). Svar: The truth table is 156
157 p q r p q (p q) r q r p (q r ) F F F F F F F F F T F T T T F T F T T T T F T T T F F F T F F T T F T T F T T F T F T T F F F T F T T T F T F T 245. Prove de Morgan s laws. Svar: Solution by truth table for (p q) = (p q) p q p q p q (p q) ( p) ( q) F F F T T T T F T F T F T T T F F F T T T T T T F F F F Solution by truth table for (p q) = (p q) p q p q p q (p q) ( p) ( q) F F F T T T T F T T T F F F T F T F T F F T T T F F F F 246. Generalise De Morgan s laws to expressions with any finite number of - or -operators, i.e., expressions on the form Hint: Use Lemma??. (p 1 p 2 p n ) and (p 1 p 2 p n ) Use truth tables to check that a. (p q) r = p (q r ). b. (p q) (q r ) = (p r ) q Svar: Mark each of the following statements as true or false: 157
158 a. a//b is always bigger than a%b. Svar: False b. (a,b) is a subset of [a,b]. Svar: True c. The fractional part of π is Svar: False d. The integer part of π is 3. Svar: True 249. Compute a //b and a %b in the cases below. a. a = 8, b = 3. b. a = 10, b = 2. c. a = 29, b = 7. d. a = 0, b = Mark each of the following statements as true or false: Svar: a. When numbers are represented in base β according to Definition??, the number 1 is always written the same way. Svar: True b. The number 16 can be written in exactly two different ways in base 7. Svar: False c. In base 16, a f < ba. Svar: True Convert the following natural numbers to the indicated bases: a. 40 to base-4 Svar: 220 b. 17 to base-5 Svar:
159 c. 17 to base-2 Svar: d to base-7 Svar: e to base-7 Svar: f. 126 to base 16 Svar: 7e 252. Convert to base-8: a Svar: 131 b Svar: 67 c Svar: Convert to base-2: a Svar: b Svar: c Svar: Convert to base-16: a Svar: 4d b Svar: c 159
160 c Svar: 29e4 d Svar: e Svar: f Svar: 0.f f Convert to base-2: Svar: a. 3c 16 Svar: b Svar: c. e51 16 Svar: d. 0.0aa 16 Svar: e Svar: f. 0.f01 16 Svar: Conversion of special numbers. a. Convert 7 to base-7, 37 to base-37, and 4 to base-4 and formulate a generalisation of what you observe. Svar: 7 = 10 7, 37 = and 4 = 10 4 Løsningsforslag: In general we have that β = 10 β for any β. In particular we have that 7 = 10 7, 37 = 10 37, 4 =
161 b. Determine β such that 13 = 10 β. Also determine β such that 100 = 10 β For which numbers a N is there a β such that a = 10 β? Svar: β = 13,β = 100 Løsningsforslag: The equation 13 = 10 β gives that β = 13 from (a). The equation 100 = 10 β gives in the same way that β = 100. For all a N we can find a β which solves a = 10 β : It is enough to set β = a Conversion of special numbers. a. Convert 400 to base-20, 4 to base-2, 64 to base-8, 289 to base-17 and formulate a generalisation of what you observe. Svar: 400 = , 4 = and 278 = b. Determine β such that 25 = 100 β. Also determine β such that 841 = 100 β. For which numbers a N is there a number β such that a = 100 β? Svar: β = 5,β = 29 c. For which numbers a N is there a number β such that a = 1000 β? 258. Mark each of the following statements as true or false: a. The number 10 β is greater in base β = 10 than in base β = 9. Svar: True b. The number 0.1 β is greater in base β = 10 than in base β = 9. Svar: False c. The number 17 β is always prime, regardless of the value of β. Svar: False d. The number is a rational number. Svar: False ln e π π 259. (Mid-way exam 2010) For which base β is it possible to represent the rational number 2/3 with a fnite sequence of digits? β = 2 β = 4 β = 10 β = 6 161
162 260. Convert the following rational numbers: a. 1/4 to base-2 Svar: 0.01 b. 3/7 to base-3 Svar: c. 1/9 to base-3 Svar: 0.01 d. 1/18 to base-3 Svar: e. 7/8 to base-8 Svar: 0.7 f. 7/8 to base-7 Svar: g. 7/8 to base-16 Svar: 0.e h. 5/16 to base-8 Svar: 0.24 i. 5/8 to base-6 Svar: Convert π to base-9. Svar: π Special rational numbers. a. For which value of β is a = b/c = 0.b β? Does such a β exist for all a < 1? And for a 1? Løsningsforslag: 0.b β is always a number in [0,1), so that such a β exists only for a < 1. Since 0.b β = b β = a = b c it follows that β = c, so that we can find a unique β for all rational a on the form a = 0.b β. b. For which rational number a = b/c does there exist a β such that a = b/c = 0.01 β? Løsningsforslag: Since 0.01 β = 1 β 2, if a = b c = 0.01 β we must have that c = bβ 2. In other words, a rational number b c can be written on the form 0.01 β if and only if c = bβ
163 c. For which rational number a = b/c is there a β such that a = b/c = 0.0b β? If β exists, what will it be? Løsningsforslag: Since 0.0b β = b β 2, if a = c d = 0.0b β we must have that c = bd. In other words, a rational number c β 2 d 0.0b β if and only if c = bd. β 2 can be written on the form 263. If a = b/c, what is the maximum length of the repeating sequence? Svar: c 1 Løsningsforslag: when we in algorithm?? obtain a b which has been seen before, we will perform the same computations again, so that the sequence will repeat. There are c possibilities for this value since we compute the remainder with c. The longest possible repeating sequence is thus one where all values of b are observed. However, the value 0 will result in the rest of the digits being 0, so the maximum length repeating sequence is obtained when the values 1,...,c 1 are observed for b in succession. This results in a repeating sequence of length c Show that if the digits of the fractional number a eventually repeat, then a must be a rational number Show that a fractional numbers in base-β with a finite number of digits is a rational number Tick the correct answer in each case. a. The equation 7 β + 8 β = 13 β is true in which numeral system? base 10 base 11 base 12 base 13 Svar: The third alternative is correct Løsningsforslag: In the equation 7 β +8 β = 13 β, the left hand side is 7+8 = 15. The right hand side is 13 β = β+3. Solving β+3 = 15 we get that β = 12, so that the third alternative is correct. b. Which of the following equations is true in base 9? = = = = 5 163
164 c. (Mid-way exam 2009) In the numeral system with base β = 8, the decimal number becomes Svar: Løsningsforslag: We can write = 5 8+1/8 = This can also be written as , so that the last alternative is the correct one Perform the following additions: Svar: a Svar: 4 7 b Svar: 13 6 c Svar: d Svar: e Svar: f Svar: 4 5 = Perform the following subtractions: Svar: a Svar: 3 8 b Svar: 11 2 c Svar:
165 d Svar: e Svar: 24 5 f g Perform the following multiplications: a Svar: b Svar: c Svar: d Svar: e Svar: f Svar: g Svar: In this exercise we will consider an alternative method for division by a natural number greater than or equal to 2. The method consists of the following simple algorithm: 1. Write the divid as a number in the base of the divisor. 2. Carry out the division. 3. Convert the quotient back to base
166 a. Use the method described above to carry out the following divisions: I) 49/7 II) 365/8 III) 4720/16 b. Formulate a general algorithm for this method of division for a given divid a and a given divisor β a. Suppose we use the method of Two s compliment to store integers with 8 bits of information. What would be the largest positive integer we would be able to store? b. suppose we execute the following short code in java, what would be the output? int a = 1; int ap = 0; while a>ap a = a + 1; ap = ap + 1; print a; Nothing, the code would loop forever, or until the machine is out of memory. a = a = a = 0 c. What would happen if you were to execute a code similar to the one in b), in Python? Nothing, the code would loop forever, or until the machine is out of memory. 166
167 a = a = a = 0 Svar: The first alternative is correct. Løsningsforslag: The machine enters an infinite loop, since Python increases the precision used for numbers when the sum of two numbers is beyond the current limit. The machine will eventually run out of memory when too much recourses are required to represent the number, but this may take some billions of years. This means that the first alternative is correct Suppose you have a computer which works in the ternary (base-3) numeral system. Can you devise a three s complement representation with 4 digits, similar to two s complement? Løsningsforslag: There is no way we can constuct a unique threes s complement in. One possibility is, in fact 4.3, to replace the representation of a negative number with the n first digits in 3 n x, where n still denotes the number of digits in x. With addition defined by neglecting digit n + 1 as in two s complement, this representation of numbers will have the same properties as two s compliment. The only difference is that the numbers now represented only will cover two thirds of the numbers with n + 1 digits: The lower third (which represents positive numbers), and the upper third (which represents negative numbers) Which of the following statements are true and which are false? a. Any integer than can be represented in the 32 bit integer format, can also be represented exactly in the 32-bit floating-point format. b. The distance between two neighbouring numbers in the IEEE 32-bit floating-point format is always c. When you add two sufficiently large floating-point numbers you will get overflow, and the result will be a large negative number We are going to write e in decimal, normal form, with 4 digits for the significand. Which of the following is the correct normal form? e e e e
168 275. Write the largest and smallest 32-bit integers, represented in two s complement, as hexadecimal numbers. Svar: Largest integer: 7f f f f f f f 16. Smallest integer: It is said that when the game of chess was invented, the emperor was so delighted by the game, that he promised the inventor to grant him a wish. The inventor said that he wanted a grain of rice in the first square of the chessboard, two grains in the second square of the chessboard, four grains in the third square, eight in the fourth and so on. The emperor considered this a very modest request, but was it? How many grains of rice would the inventor get? Translate this into a problem of converting numbers between different bases, and solve it. (Hint: A chessboard is divided into 64 squares) Write the following numbers (or approximations of them) in normal form, using both 4 and 8 digits a Svar: b Svar: c Svar: d e f. e 10π 278. Redo exercise 277d, but write the number in binary normal form. Svar: Which of the following statements are true and which is false: a. A text encoded in ASCII will display correctly if it is treated as a text encoded in ISO Latin 1. b. A text encoded in ISO Latin 1 will display correctly if it is treated as a text encoded in ASCII. 168
169 c. The UTF-8 code " "corresponds to a sequence of 4 characters. d. A text written with Norwegian letters (standard Latin alphabet, with the addition of the letters Ê, and  ) encoded in UTF-8 will sometimes require more space than if encoded in ISO Latin Which encoding? a. (Exam 2007) In a text the are three different symbols, encoded with one of the methods for representation of text discussed in this section. It turns out that one symbol is represented with one byte, another with two bytes and the third one with three bytes. Which of the following statements is correct? The symbols could have been encoded with ASCII The symbols could have been encoded with UTF-8 The symbols could have been encoded with UTF-16 The symbols could have been encoded with ISO-Latin 1. b. (Continuation exam 2007) In which of the following encoding schemes is the Norwegian letter encoded with two bytes? ASCII UTF-8 ISO Latin 1 UTF-32 c. (Continuation exam 2011) A text is stored in 4 different files with the encoding schemes ISO Latin 1, UTF-8, UTF-16, UTF-32. Which of the following statements is then true? The file encoded with ISO-Latin 1 will be the largest. The file encoded with UTF-8 will be the largest. The file encoded with UTF-16 will be the largest. The file encoded with UTF-32 will be the largest Determine the UTF-8 encodings of the Unicode characters with the following code points: 169
170 a. 5a 16. Svar: = 5a 16 Løsningsforslag: Since 5a 16 7f 16, this is encoded with one byte, so that the UTF-8 encoding is the number itself, i.e. 5a 16. b. f5 16. Svar: = c3b5 16 Løsningsforslag: We have that f f f 16, so that two bytes are used in the UTF8-encoding. Since f 5 16 = , we have that the UTF8-encoding is = c3b5 16. c. 3f8 16. Svar: = c f b8 16 Løsningsforslag: We have that f f f 16, so that two bytes are used in the UTF8-encoding also here. Since 3f 8 16 = , we have that the UTF8-encoding is = c f b8 16. d. 8f Svar: = e8bcb7 16 Løsningsforslag: We have that f f f f f 16, so that three bytes are used in the UTF8-encoding also here. Since 8f = , we have that the UTF8-encoding is = e8bcb Determine the UTF-16 encodings of the Unicode characters in exercise 281. Svar: = 005a = 00f = 03f = 8f In this exercise you may need to use the Unicode table which can be found on the web page a. Suppose you save the characters Ê, and  in a file with UTF-8 encoding. How will these characters be displayed if you open the file in an editor using the ISO Latin 1 encoding? Svar: ÔøΩ : ÃÔøΩ,ÔøΩ : Ãc,ÔøΩ : à Løsningsforslag: These characters have code points e6 16 = , f 8 16 = , and e5 16 = All of them are stored with 2 bytes in UTF-8 The UTF8-encoding of Ê is = c3a6 16, 170
171 which corresponds to the two characters inthei SOLatin1char acter set.t heut F 8 encoding o f i s = c3b8 16, which corresponds to the two characters ΠintheI SOLatin1char acter set.t heut F 8 encoding o f Ê i s = c3a5 16, which corresponds to the two characters ĹintheI SOLatin1char acter set. b. What will you see if you do the opposite? Svar: Nothing or error message; these codes are not valid UTF-8 codes. Løsningsforslag: None of the three codepoints for Ê,, Â, are seen to be valid UTF8-codes. c. Repeat (a) and (b), but use UTF-16 instead of UTF-8. Svar: ÔøΩ : NULÔøΩ,ÔøΩ : NULÔøΩ,ÔøΩ : NULÔøΩ;eachchar acter i spreceded(or f ollowed f or LE) 16encoding s(tooshor t). Løsningsforslag: All three characters are also stored with 2 bytes in UTF- 16, and as 00e6 16, 00f 8 16, and 00e5 16, respectively. These are shown as Ê,, and Â, respectively. The other way, the ISO Latin1 encoding of each of the three characters is too short to be accepted as a UTF-16 encoding. d. Repeat (a) and (b), but use UTF-16 instead of ISO Latin 1. Svar: The conversion from UTF-8 to UTF-16 yields the following Hangul symbols: ÔøΩ :, ÔøΩ :, ÔøΩ : The conversion from UTF-16 to UTF-8 yields illegitimate codes, though there will be an allowed null character preceding (or following for LE) each prohibited letter. Løsningsforslag: Assume that the characters are stored with UTF-8. As shown in (a), the UTF8-characters are c3a6 16, c3b8 16, and = c3a5 16, which are the valid two-byte Unicode characters a6, b8, and a5. Conversely, assume that the characters are stored with UTF-16. The first byte in the code for Ê, indicates that it shoould be stored with 3 bytes, but then the second byte should start with 10, which it does not. The same applies for Â. Finally, for the code for, there are no bytes in UTF-8 which start with 11111, so that all characters are invalid UTF-8 characters Encoding your name. a. Write down the hexadecimal representation of your first name in ISO Latin 1, UTF-8, and UTF-16 with BE (If your first name is only three letters or less, do your last name as well, include a blank space between the names). 171
172 b. Consider the first 3 bytes in the codes for your name (not counting the specific BE-code for UTF-16) and view each of them as an integer. What decimal numbers do they correspond to? Can these numbers be represented as 32-bit integers? c. Repeat b) for the first 4 bytes of your name (not counting the specific BE-code) In this exercise you are going to derive an algorithm to find the nth character in a UTF-8 encoded file. We assume that the file is given as an array of 8-bit integers, i.e., each integer is in the range a. The UTF-8 encoding scheme uses a variable bit length (see Fact??). In order to determine whether a byte represents the start of a new character, one must determine in which integer interval the byte lies. Determine which integer intervals denote a new character and which intervals denote the continuation of a character code. b. Derive an algorithm for finding the nth character. Your algorithm may begin as follows: counter = 0 while counter < n: get a new byte if byte is in correct interval: act accordingly else: act accordingly c. In this exercise you are going to write a Python script for finding the n-th sign in an UTF-8 encoded file. You may use this layout: # Coding: utf-8 # This part of the program creates a list bytelist where each # element is the value of the corresponding byte in the file infile = open( filename, rb ) bytelist = [] 172
173 while True: byte = infile.read(1) if not byte: break bytelist.app(ord(byte)) # Your code goes here. The code should runt through the byte list, # and match each sequence of bytes to a corresponding character. # When you reach the n-th character, you should compute the code # point, store it in the variable character and print it. character = unichr(character) print character d. Repeat the exercise for the UTF-16 encoding scheme 286. You are given the following hexadecimal code: Determine whether it is a text encoded in UTF-8 or UTF-16. Løsningsforslag: We have that = This is clearly a valid UTF-8 encoding of 5 ASCII characters. Since 5 bytes are used, it can not be a UTF-16 code, since that would require an even number of bytes being used You are given the following binary code: What does this code translate to if it is a text encoded in a. UTF-8? b. UTF-16? 288. The following sequence of bytes represent a UTF-8 encoded text, but some of the bytes are wrong. Find which ones they are, and explain why they are wrong: 173
174 41 C C C Løsningsforslag: We have that 41 C C C = The first byte, , is a valid UTF-8 character. The next two bytes, , is a valid two-byte UTF-8 character. The next byte, , is again a valid UTF-8 character. the next two bytes, are not valid, since the second byte should start with 10 when the first starts with In this exercise, we want to create a fixed length encoding scheme for simple Norwegian text. Our set of characters must include the 29 uppercase Norwegian letters, a space character and a period character. a. How many bits are needed per character to represent this character set? b. Now assume that we also want to add the lowercase letters, the numbers 0-9 and a more complete set of notation characters, so that the total number of characters is 113. How many bits are now needed per character? c. How many bits are needed per character in a fixed length encoding scheme with n unique characters? (Hint: The result in exercise?? might be useful.) 290. Mark each of the following statements as true or false. a. The number 8.73 truncated to an integer is becomes 9. b. The method taught in school of rounding decimal numbers to the nearest integer and rounding 0.5 up to 1 gives the smallest statistical error possible. c. Rounding will always give a results which is at least as large as the result of truncation. 174
175 291. (Mid-term 2011) Which of the following expressions may give large errors for at least one value of x, when calculated on a machine using floating point arithmetic? x x 2 + x 4 a = x/(1 + x 2 ) 1/2 + sin( x 2 ) Svar: The last expression. Løsningsforslag: The last expression may give large relative error when calculated on a machine using floating point arithmetic, since it is possible for sin( x 2 ) to be close to 1/2 (cancellation). The other expressions can not give cancellation Rounding and truncation. a. Round to 1 digit. b. Round to 1 digit. c. Round 100 to 1 digit. d. Round to 3 digits. e. Truncate to 3 digits. f. Round 4525 to 3 digits Try to describe a rounding rule that is symmetric, i.e., it has no statistical bias Floating-point models for other bases. a. Formulate a model for floating-point numbers in base β. Svar: Normalised number in base β: A nonzero number a is written as a = α β n where β 1 α < 1. Løsningsforslag: A normalised number in base β is represented as α β n where n is a one digit number, and α is a number between β 1 and 1 represented with a four digit number in base β (0.1 = 10 1 was exchanged with β 1 ). 175
176 b. Generalise the rule for rounding of fractional numbers in the decimal system to the octal system and the hexadecimal system. Løsningsforslag: In any numeral system we have three cases to consider when defining rounding rules. Note also that it is sufficient to define rounding for two-digit fractional numbers. In the octal numeral system the three rules are: 1. A number (0.d 1 d 2 ) 8 is rounded to 0.d 1 if the digit d 2 is 0, 1, 2 or If d 1 < 7 and d 2 is 4, 5, 6, or 7, then (0.d 1 d 2 ) 8 is rounded to 0. d 1 where d 1 = d A number (0.7d 2 ) 8 is rounded to 1.0 if d 2 is 4, 5, 6, or 7. In the hexadecimal numeral system the rules are similar: If the last digit is one of 8, 9, a,b,c,d,e, or f, round up, otherwise round down. c. Formulate the rounding rule for fractional numbers in the base-β numeral system From the text it is clear that on a computer, the addition ɛ will give the result 1.0 if ɛ is sufficiently small. Write a computer program which can help you to determine the smallest integer n such that n gives the result 1.0 Svar: One possible program: n := 1; while n > 1.0 n := n + 1; print n; 296. Consider the simple algorithm x = 0.0; while x 2.0 print x x = x + 0.1; What values of x will be printed? Implement the algorithm in a program and check that the correct values are printed. If this is not the case, explain what happened. Løsningsforslag: Code in Python is x=0.0 while x<= 2.0: print x x=x
177 In my program the last value 2.0 is not written. The explanation is that 0.1 can not be represented exactly by the computer. What actually is the case here is that the machine represents 0.1 with a number slightly bigger than 0.1. When this number is added with itself 20 times, we have a number which is bigger than 2.0, so the number is not printed. 2.0 can, however, be represented exactly by the computer Rounding and different laws. a. A fundamental property of real numbers is given by the distributive law (x + y)z = xz + yz. (1) In this problem you are going to check whether floating-point numbers obey this law. To do this you are going to write a program that runs through a loop times and each time draws three random numbers in the interval (0,1) and then checks whether the law holds (whether the two sides of (1) are equal) for these numbers. Count how many times the law fails, and at the, print the percentage of times that it failed. Print also a set of three numbers for which the law failed. b. Repeat (a), but test the associative law (x + y) + z = x + (y + z) instead. c. Repeat (a), but test the commutative law x + y = y + x instead. d. Repeat (a) and (b), but test the associative and commutative laws for multiplication instead Mark each of the following statements as true or false. a. The absolute error is always larger than the relative error. b. If the relative error is 0, then the absolute error is also 0. c. If ā and ã are two different approximations to a, with relative errors ɛ 1 and ɛ 2, then the relative error of ā when compared to ã is less than or equal to ɛ 1 + ɛ 2. d. If ā and ã are two different approximations to a, with absolute errors ɛ 1 and ɛ 2, then the absolute error of ā when compared to ã is less than or equal to ɛ 1 + ɛ Suppose that ã is an approximation to a in the problems below, calculate the absolute and relative errors in each case, and check that the relative error estimates the number of correct digits as predicted by observation??. 177
178 a. a = 1, ã = Svar: r = Løsningsforslag: The absolute error is a ã = = The relative error is a ã a = = The relative error can also be written as , and observation?? says that about the 3 most significant digits in a and ã should agree. This is not so far from the truth in this case, since (where we have included the three most significant digits) will be rounded to b. a = 24, ã = Svar: r Løsningsforslag: The absolute error is a ã = = The relative error is a ã a = = The relative error can also be written as , and observation?? says that about the 2 most significant digits in a and ã should agree. This is in fact the case, since with the two most significant digits gives 24. c. a = 1267, ã = Svar: r Løsningsforslag: The absolute error is a ã = = The relative error is a ã a = = The relative error can also be written as , and observation?? says that about the 4 most significant digits in a and ã should agree. This is in fact the case, since with the two most significant digits gives d. a = 124, ã = 7. Svar: r 0.94 Løsningsforslag: The absolute error is a ã = = 117. The relative error is a ã a = = The relative error can also be written as , and observation?? says that no significant digits in a and ã should agree. This is the case here The Vancouver stock exchange devised a short-lived index (weighted average of the value of a group of stocks). At its inception in 1982, the index was given a value of After 22 months of recomputing the index and truncating to three decimal places at each change in market value, the index stood at , despite the fact that its true value should have been Find the relative error in the stock exchange value In the 1991 Gulf War, the Patriot missile defence system failed due to roundoff error. The troubles stemmed from a computer that performed the tracking 178
179 calculations. The computer s internal clock generated integer values that were converted to real time values by multiplying the integer values by 0.1, with the arithmetic carried out in binary. The approximation which was used for 0.1 was = a. Find the absolute and relative error in this approximation. b. The computed time values corresponded to time given in tenths of a second and was therefore calculated 10 times every second by the equivalent of the naive code c = / while not ready t = t + i t c where i t is the integer increment of the internal clock. Find the accumulated error after 1 hour. c. Find an alternative algorithm that avoids the accumulation of roundoff error. After the system had been running for 100 hours, an error of seconds had accumulated. This discrepancy caused the Patriot system to continuously recycle itself instead of targeting properly. As a result, an Iraqi Scud missile could not be targeted and was allowed to detonate on a barracks, killing 28 people a. (Mid-term 2011) The number is the same as /2 Svar: 3/2 Løsningsforslag: We can write = (5 5)(5 5) Therefore, the last alternative is the correct one = = 3 2.
180 b. (Mid-term 2011) Only one of the following statements is true, which one? Computers will never give round off errors as long as we use positive numbers. There is no limit to how lagre numbers we can work with on a given computer. With 64-bit integers we van represent numbers of size up to We can represent larger numbers with 64-bit floating point numbers than with 64-bit integers. Svar: The last alternative is the correct one. Løsningsforslag: The last alternative is the correct one. The reason is that several bits are allocated for the exponent, see Fact 4.8. The first alternative is wrong, positive numbers can also give roundoff errors. The second alternative is wrong because we typically have limitations on the computer in the significand and the exponent, and even if the types can expand the bits used for these as in Python, the computer has at the a limited amount of memory. The third alternative is wrong, since 64-bit integers represents numbers in the interval [ 2 63,2 63 1] (Fact 4.2) Identify values of x for which the formulas below may lead to large roundoff errors, and suggest alternative formulas which do not have these problems. a. x + 1 x. Løsningsforslag: If x is very large we will in the expression x + 1 x subtract two large numbers very close to each other. According to observation?? we then can loose precision with many digits (i.e. cancellation). If we multiply with x x up and down we get, where we x+1+ x have avoided the problem of subtracting two numbers close to each other. b. ln x 2 ln(x 2 + x). Løsningsforslag: The fomula ln x 2 ln(x 2 + x) is problematic for large values of x since then the two logarithms will become almost equal and we get cancellation. Using properties of the logarithm, the expression can be rewritten as ( ln x 2 ln(x 2 + x) = ln x 2 x 2 + x ) ( = ln which will not cause problems with cancellation. x x + 1 ) 180
181 c. cos 2 x sin 2 x. Løsningsforslag: We can write cos 2 x sin 2 x = cos(2x),so that we avoid subtraction of two almost equal numbers near x = π Suppose you are going to write a program for computing the real roots of the quadratic equation ax 2 +bx +c = 0, where the coefficients a, b and c are real numbers. The traditional formulas for the two solutions are x 1 = b b 2 4ac 2a, x 2 = b + b 2 4ac. 2a Identify situations (values of the coefficients) where the formulas do not make sense or lead to large round-off errors, and suggest alternative formulas for these cases which avoid the problems The binomial coefficient ( n i ) is defined as ( ) n n! = i i!(n i )! where n 0 is an integer and i is an integer in the interval 0 i n. The binomial coefficients turn up in a number of different contexts and must often be calculated on a computer. Since all binomial coefficients are integers (this means that the division in (2) can never give a remainder), it is reasonable to use integer variables in such computations. For small values of n and i this works well, but for larger values we may run into problems because the numerator and denominator in (2) may become larger than the largest permissible integer, even if the binomial coefficient itself may be relatively small. In many languages this will cause overflow, but even in a language like Python, which on overflow converts to a format in which the size is only limited by the resources available, the performance is reduced considerably. By using floating-point numbers we may be able to handle larger numbers, but again we may encounter too big numbers during the computations even if the final result is not so big. An unfortunate feature of the formula (2) is that even if the binomial coefficient is small, the numerator and denominator may both be large. In general, this is bad for numerical computations and should be avoided, if possible. If we consider the formula (2) in some more detail, we notice that many of the numbers cancel out, ( ) n 1 2 i (i + 1) n = i 1 2 i 1 2 (n i ) = i i n n i. (2) 181
182 Employing the product notation we can therefore write ( n i ) as ( ) n n i i + j =. i j =1 j a. Write a program for computing binomial coefficients based on this formula, and test your method on the coefficients ( ) 9998 = , 4 ( ) = , 70 ( ) 1000 = Why do you have to use floating-point numbers and what results do you get? b. Is it possible to encounter too large numbers during those computations if the binomial coefficient to be computed is smaller than the largest floating-point number that can be represented by your computer? c. In our derivation we cancelled i! against n! in (2), and thereby obtained the alternative expression for ( n) i. Another method can be derived by cancelling (n i )! against n! instead. Derive this alternative method in the same way as above, and discuss when the two methods should be used (you do not need to program the other method; argue mathematically) A close relative of the Fibonacci numbers is called the Lucas numbers, and these are defined by the difference equation L n+2 = L n+1 + L n, L 0 = 2, L 1 = 1. Write a program which prints the following information: a. The 18th Lucas number. b. The first Lucas number greater than 100. c. The value of n for the number in (b). 182
183 d. The Lucas number closest to Mark each of the following statements as true or false. a. There will always be major round-off errors when we solve second order difference equations numerically. b. When solving difference equations numerically, it is impossible to know when we will up with completely wrong answers due to round-off errors Løsningsforslag: The code can look as follows: #a xpp=1.0 xp=2.0/3.0 for n in range(100): x=(-4.0*xp+4.0*xpp)/3.0 xpp=xp xp=x print xp #b x=1.0 for n in range(100): x=(1.0+x/3.0)/3.0 print x a. (Mid-term 2009) We have the difference equation 3x n+2 + 4x n+1 4x n = 0, x 0 = 1, x 1 = 2/3 and simulate this with 64-bit floating-point numbers on a computer. For large n, the computed solution x n will give the result underflow 1 (2/3) n overflow and then NAN Svar: overflow and then NAN. 183
184 Løsningsforslag: The characteristic equation is 3r 2 + 4r 4 = 0, which has roots r = 4± = 2±4 3. The roots are thus 2 and 2/3, so that the solution to the difference equation is x n = C ( 2) n + D(2/3) n. The initial values give C + D = 1 2C D = 2/3, which gives that 8 3 D = 8 3, so that D = 1 and C = 0. The solution is thus x n = (2/3) n. This will go to zero, but due to roundoff in the second initial condition there will be a term on the form ˆɛ( 2) n also contributing in the simulation, so that we will will eventually get overflow. We will then get NAN, since we at the substract from or vice versa). The last alternative is thus correct. b. (Mid-term 2009) We have the difference equation 3x n+1 x n /3 = 1, x 1 = 1 and simulate this with 64-bit floating point numbers on a computer. For large n, the computed x n solution will then approach n 1 0 3/8 Svar: 3/8 Løsningsforslag: It is straightforward to check that the exact solution is x n = ( 1 ) n. 8 9 It is clear that simulations will converge to 3/8. c. (Mid-term 2010) We have the difference equation x n+1 x n /3 = 2, x 0 = 2, and simulate this with 64-bit floating-point numbers on a computer. For all n larger than a certain limit, the computed solution x n will then give the result n 184
185 309. In each of the cases, find the analytical solution of the difference equation, and describe the behavior of the simulated solution for large values of n. a. x n x n = 2, x 0 = 2 Svar: x n = 3 3 n. b. x n+2 6x n x n = 1, x 0 = 1/7, x 1 = 1/7 Svar: x n = 1/7. c. 3x n+2 + 4x n+1 4x n = 0, x 0 = 1, x 1 = 2/3 Svar: x n = (2/3) n In this exercise we are going to study the difference equation x n+1 3x n = 5 n, x 0 = 5/14. (3) a. Show that the general solution of (3) is x n = C 3 n n and that the initial condition leads to the solution x n = n. b. Explain what will happen if you simulate equation 3 numerically. c. Do the simulation and check that your prediction in (b) is correct. Løsningsforslag: The code can look as follows: N=40 x=-5.0/14 print x for n in range(n): x=3.0*x+5**(-n) print x 311. We consider the Fibonacci equation with nonstandard initial values x n+2 x n+1 x n = 0, x 0 = 1, x 1 = (1 5)/2. (4) 185
186 a. Show that the general solution of the equation is ( 1 + ) n ( 5 1 ) n 5 x n = C + D, 2 2 and that the initial values select the solution ( 1 ) n 5 x n =. 2 Løsningsforslag: The characteristic equation is r 2 r 1 = 0, which has roots r = 1± = 1± 5 2. This means that we have two different real roots, so that the general solution is The two initial values give ( 1 + ) n ( 5 1 ) n 5 x n = C + D. 2 2 C C + D = 1 + D Substituting the first in the second gives C = = (1 5)/2, so that C = 0 and D = 1. This gives the solution x n = ( ) 1 5 n. 2 b. What will happen if you simulate (4) on a computer? Løsningsforslag: Due to rounding in the second initial condition, the computer will simulate values of the form ( 1 + ) n 5 1 x n = ˆɛ + (1 ˆɛ)( ) n This means that the values of x n eventually will overflow. In the beginning of the calculations, ) the values seem to converge to zero, since the term (1 n ˆɛ) dominates in the beginning, and this term converges to zero. (
187 c. Do the simulation and check that your predictions are correct. Løsningsforslag: The code can look as follows: from math import sqrt xpp=1.0 xp=(1-sqrt(5.0))/2.0 for n in range(100): x=xpp+xp xpp=xp xp=x print xp 312. We have the difference equation x n x n x n = 0, x 0 = 1, x 1 = 1/15. (5) a. Determine the general solution of (5) as well as the solution selected by the initial condition. Svar: Solution determined by the initial conditions: x n = 15 n. Løsningsforslag: The characteristic equation is r r + 1 = 0, which has roots 2 5 ± r = 2 so that r = 1 3 eller r = equation is x n = A ( 1 15) n + B ( 1 3 = 2 5 ± = ± 4 15 = ± 2 15,. Therefore the general solution to the difference ) n. The initial values x0 = 1, x 1 = 1 15 give A + B = A B = These equations can also be written as A + B = 1 A + 5B = 1. We quickly see that the dolution to this is A = 1, B = 0, so that the solution to the difference equation is x n = ( 1 15) n = 15 n. 187
188 b. Why must you expect problems when you do a numerical simulation of the equation? Løsningsforslag: The other initial condition cannot be represented exactly on the computer, so that the computer instead will find a solution on the form ( ) 1 n ( ) 1 n xˆ n = (1 ˆɛ) + ˆɛ, 15 3 where ˆɛ is a small number representing the roundoff error committet by the computer. When n becomes large, the error ˆɛ ( 1 n 3) dominates in this expression, which explains why we must expect numerical inaccuracies for large n. Note that the absolute error is not large since ˆɛ ( 1 n 3) is a small number, but that the relative error is very large since, since ˆɛ ( 1 n 3) is relatively much larger than ( 1 n 15) for large n. c. Determine approximately the value of n when the numerical solution has lost all significant digits. Svar: n 24. Løsningsforslag: ˆɛ represents approximately the smallest number the machine can represent. If we use 64 bits this corresponds to We have lost all significant digits when the error ˆɛ ( 1 n 3) becomes larger ) n, i.e ( ) 1 n ( 3 > 1 n. 15) This corresponds to ln5 24. The arguments given here are not exact. For example, it can be that the estimate for ˆɛ is not very exact. that the actual solution ( n > 10 17, which gives n > 17ln10 d. Perform the numerical simulation and check that your predictions are correct. Løsningsforslag: The code can look as follows: N=100 xpp=1.0 xp=1.0/15 for i in range(2,n): x=2.0*xp/5+xpp/45 print i,x xpp=xp xp=x 313. In this exercise we consider the difference equation x n x n+1 + x n = 0, x 0 = 1, x 1 = 1/2. 188
189 a. Determine the general solution, and the solution corresponding to the initial conditions. Svar: Solution determined by the initial conditions: x n = 2 n. b. What kind of behaviour do you expect if you simulate the equation numerically? c. Do the simulation and explain your results. Løsningsforslag: The code can look as follows: N=100 xpp=1.0 xp=0.5 for k in range(2,n): x=5.0*xp/2-xpp print k,x xpp=xp xp=x 314. Mark each of the following statements as true or false. a. Huffman coding uses a special code to separate each symbol in a text. b. Huffman coding is the most optimal coding scheme based on binary trees. c. Because there is no ambiguity in the Huffman algorithm we do not need to store the code for each symbol in a text, only how many times each symbol occurs. d. The Huffman algorithm assigns codes to symbols in the order of most frequent symbol to least frequent symbol Only one of the following statements is true. Which one? Huffman coding allows you to store information with an absolute minimum amount of bits. Huffman coding can only be used to store letters, not numbers. In Huffman coding, the most frequent symbols in a text get the shortest codes. A node in a binary tree can have anywhere from 2 to 5 subtrees. 189
190 e r t h a n p o 2 2 l m y i 1 1 w d Figur 6: The Huffman tree for the text there are many people in the world In this exercise we are going to use Huffman coding to encode the text There are many people in the world, including the spaces. a. Compute the frequencies of the different symbols used in the text. Løsningsforslag: f (t) = 2, f (h) = 2, f (e) = 6, f (r ) = 3, f ( ) = 6, f (a) = 2, f (m) = 1, f (n) = 2, f (y) = 1, f (p) = 2, f (o) = 2, f (l) = 2, f (i ) = 1, f (w) = 1, f (d) = 1. b. Use algorithm?? to determine the Huffman tree for the symbols. Løsningsforslag: An example of a Huffman tree for this text can be seen in figure 6: c. Determine the Huffman coding of the complete text. How does the result compare with the entropy? Løsningsforslag: The Huffman coding for the text there are many people 190
191 in the world"is then: The entropy is: H = (6) which means an optimal coding of the text would use bits per symbol. There are 34 symbols so the minimum coding would consist of 15 bytes and 4 bits. The Huffman coding above gave 15 bytes and 5 bits of information, so this coding is very good We can generalise Huffman coding to numeral systems other than the binary system. a. Suppose we have a computer that works in the ternary (base-3) numeral system; describe a variant of Huffman coding for such machines. Svar: Use ternary trees instead of binary ones. (Each tree has either zero or three subtrees/children). b. Generalise the Huffman algorithm so that it produces codes in the base-n numeral system. Svar: Use n-nary trees. (Each tree has either zero or n subtrees/children) 318. In this exercise we are going to do Huffman coding for the text given by x = {AB AC ABC A}. a. Compute the frequencies of the symbols, perform the Huffman algorithm and determine the Huffman coding. Compare the result with the entropy. Løsningsforslag: f (A) = 4, f (B) = 2, f (C ) = 2, One of the four possible Huffman codings are: 191
192 The entropy is H = 1.5 (7) This gives an optimal coding with 12 bits for 8 symbols, which is just what the Huffman coding gave. b. Change the frequencies to f (A) = 1, f (B) = 1, f (C ) = 2 and compare the Huffman tree with the one from (a). Løsningsforslag: Dividing all the frequencies by 2 and interchanging A with C in the tree in (a) gives the tree for this problem. We can now use the same Huffman codes (with the code of A interchanged by the code of C), and Huffman coding is clearly still optimal (the entropy is unchanged) Mark each of the following statements as true or false. a. The text "AAAABBBB"has less entropy than AABAABBBA. Svar: The statement is false. Løsningsforslag: The first text has probabilities p(a) = 0.5, p(b) = 0.5, so that the entropy is 0.5log 2 (0.5) 0.5log 2 (0.5) = 1. The second text has probabilities p(a) = 5/9, p(b) = 4/9, so that the entropy is 5/9log 2 (5/9) 4/9log 2 (4/9) = The statement is therefore false. b. A text consisting of only one symbol repeated an arbitrary number of times will always have 0 entropy. Svar: The statement is true Løsningsforslag: We have that the probability of the symbol is p(a) = 1. Since log 2 (1) = 0, the informtaion entropy is 0, so that the statement is true. c. In general, long texts will have a higher entropy than short texts. Svar: The statement is false Løsningsforslag: The statement is false. As an example, if we repeat a short text many times, the information entropy is unchanged. d. The entropy of the answer to this question will be more than 2.3. Svar: The statement is false. Løsningsforslag: The answer to this question consists of a value of true or 192
193 false. If p is the probability of true, the information entropy is p log 2 p (1 p)log 2 (1 p). If p 1 p, we have that p log 2 p (1 p)log 2 (1 p) < p log 2 (1 p) (1 p)log 2 (1 p) = log 2 (1 p) < 1. Similarly when p < 1 p. The statement is therefore false (Exam 2010) The entropy of a text gives the minimum number of bits needed per symbol that the text is coded with. If we use Huffman-coding based on the frequency of the symbols in the text, which of these texts will not achieve a minimal amount of bits per symbol? AABB ABCC ABBB ABCD Løsningsforslag: The information entropy for the first text is 0.5log log = 1. Clearly Huffman coding here uses 1 bit per symbol also, so this achieves a minimum number of bits per symbol. The information entropy for the second text is 2( 0.25log ) 0.5log = 1.5. Huffman coding here uses codes of length l(a) = l(b) = 2, and l(c ) = 1, so that it uses p(a)l(a) + p(b)l(b) + p(c )l(c ) = = 1.5 bits per symbol, so this achieves a minimum number of bits per symbol as well. The information entropy for the third text is 0.25log log Clearly Huffman coding here uses 1 bit per symbol, so this does not achieve a minimum number of bits per symbol. The information entropy for the fourth text is 4( 0.25log ) = 2. Clearly Huffman coding here uses 2 bits per symbol also, so this achieves a minimum number of bits per symbol Use the relation 2 log 2 x = x to derive a formula for log 2 x in terms of natural logarithms. Svar: log 2 x = ln x/ln a. Search the www and find the probabilities of the different letters in the English alphabet. b. Based on the probabilities you found in (a), what is the information entropy of an English text? 193
194 c. Try to repeat (a) and (b) for your own language Mark each of the following statements as true or false. a. For long texts the number of bits per symbol required by the arithmetic coding algorithm approaches the minimum given by the entropy, provided the probability distribution of the symbols is correct. b. Because computers have limited precision, we can only code very short texts (less than 64 characters) when using arithmetic coding. c. If we want to decode an aritmethically coded text, we need to know which probabilities were used as well as the ordering of the symbols In this exercise we use the two-symbol alphabet A = {A,B}. a. Compute the frequencies f (A) and f (B) in the text x = {AAAAAAAB AA} and the probabilities p(a) and p(b). Svar: f (A) = 9, f (B) = 1, p(a) = 0.1, p(b) = 0.9, Løsningsforslag: Clearly we have that f (A) = 9, f (B) = 1, so that p(a) = 9/10, p(b) = 1/10. b. We want to use arithmetic coding to compress the sequence in (a); how many bits do we need in the arithmetic code? Svar: 6 bits Løsningsforslag: We have that log 2 ( ) + 1 = 6, so that 6 bits are needed. c. Compute the arithmetic code of the sequence in (a). Svar: Løsningsforslag: The first seven A s restrict us to the interval [0,0.9 7 ]. The next B restricts us to the interval [0.9 8,0.9 7 ], and the two last A s restrict us further to the interval [0.9 8, ( )]. The midpoint in this interval is ( )/ The first bit in this is clearly
195 To compute the second bit we compute , so that the second bit is 1. We then compute , so that the third bit is 1. We then compute , so that the fourth bit is 1. We then compute , so that the fifth bit is 0. Finally we compute , so that the sixth and final bit is 0. The arithmetic code is thus (we could here have omitted the two trailing zeros in the arithmetic code as well, since and correspond to the same number) The four-symbol alphabet A = {A,B,C,D} is used throughout this exercise. The probabilities are given by p(a) = p(b) = p(c ) = p(d) = a. Compute the information entropy for this alphabet with the given probabilities. Svar: H = 2 Løsningsforslag: The information entropy is log 2 (0.25) = 2. b. Construct the Huffman tree for the alphabet. How many bits per symbol is required if you use Huffman coding with this alphabet? Svar: 2 bits per symbol c. Suppose now that we have a text x = {x 1,..., x m } consisting of m symbols taken from the alphabet A. We assume that the frequencies of the symbols correspond with the probabilities of the symbols in the alphabet. How many bits does arithmetic coding require for this sequence and how many bits per symbol does this correspond to? Svar: 2m + 1 bits 2m+1 m 2 bits per symbol Løsningsforslag: Arithmetic coding requires log 2 (0.25 m ) + 1 = 2m + 1 bits, so that we require 2m+1 m bits per symbol. When m is large this is very close to 2. d. The Huffman tree you obtained in (b) is not unique. Here we will fix a tree so that the Huffman codes are c(a) = 00, c(b) = 01, c(c ) = 10, c(d) =
196 Compute the Huffman coding of the sequence ACDBAC. Svar: e. Compute the arithmetic code of the sequence in (d). What is the similarity with the result obtained with Huffman coding in (d)? Svar: Løsningsforslag: We map A to the interval [0,0.25], B to the interval [0.25,0.5], C to the interval [0.5,0.75], D to the interval [0.75,1]. This means that the four intervals correspond to numbers where the first bits are 00, 01, 10, and 11, respectively. Note that these are exactly the Huffman codewords for the four letters. Clearly this also means that, when we refine the arithmetic code with a new letter, this means that we simply add the corresponding bits to the code This means that the arithmetic code is the same as the Huffman code, with the exception that we add a bit at the. This bit represents that we restrict to the midpoint on the interval, which is achieved if we set the bit to 1 (i.e. 0.b1 is the midpoint in [0.b,0.(b + 1)]) The three-symbol alphabet A = {A, B,C } with probabilities p(a) = 0.1, p(b) = 0.6 and p(c ) = 0.3 is given. A text x of length 10 has been encoded by arithmetic coding and the code is What is the text x? Svar: BCBBCBBBCB Løsningsforslag: The letters A,B, and C correspond to the intervals [0, 0.1], [0.1, 0.7], and [0.7,1], respectively. The number corresponds to = This lies in the second interval, so that the first letter is B. We now apply the mapping h 2 ( ) = ( )/( ) = , and this value lies in the third interval, so that the second letter is C. We now apply the mapping h 3 ( ) = ( )/(1 0.7) = , and this value lies in the second interval, so that the third letter is B. 196
197 We now apply the mapping h 2 ( ) = ( )/( ) = , and this value lies in the second interval, so that the forth letter is B. We now apply the mapping h 2 ( ) = ( )/( ) = , and this value lies in the third interval, so that the fifth letter is C. We now apply the mapping h 3 ( ) = ( )/(1 0.7) = , and this value lies in the second interval, so that the sixth letter is B. We now apply the mapping h 2 ( ) = ( )/( ) = , and this value lies in the second interval, so that the seventh letter is B. We now apply the mapping h 2 ( ) = ( )/( ) = , and this value lies in the second interval, so that the eigth letter is B. We now apply the mapping h 2 ( ) = ( )/( ) = , and this value lies in the third interval, so that the nineth letter is C. We now apply the mapping h 3 ( ) = ( )/(1 0.7) = , and this value lies in the second interval, so that the tenth letter is B. In summary, the text is BCBBCBBBCB We have the two-symbol alphabet A = {A, B} with p(a) = 0.99 and p(b) = Find the arithmetic code of the text 99 times {}}{ AAA AAA B. Svar: Løsningsforslag: The first 99 A s restrict us to the interval [0, ]. The last B restricts us to the interval [ , ]. The arithmetic code is thus ( )/2 = We need log 2 ( = 10 bits for the arithmetic code. 197
198 Clearly the first bit is 0. We compute , so that the second bit is 1. We then compute so that the third bit is 0. We then compute = so that the fourth bit is 1. We then compute , so that the fifth bit is 1. We then compute , so that the sixth bit is 1. We then compute , so that the seventh bit is 1. We then compute , so that the eighth bit is 0. We then compute , so that the nineth bit is 0. Finally we compute , so that the final bit is 0. The arithmetic code is thus Mark each of the following statements as true or false. a. If we sample the function sin(2π800t) with 1000 samples per second it may be perfectly reconstructed. b. The CD-format has a high enough sample rate to reconstruct any sound that is perceivable by the human ear (Exam 2009) A program generates a digital sound by measuring the sound times per second (in one channel, i.e. not stereo), and each measurement is stored as a 32 bit integer. For each minute of music, this gives a total of bytes bytes bytes bytes 198
199 330. Mark each of the following statements as true or false. a. The error bound in the bisection method is reduced by a factor 2 for each iteration. b. When using the bisection method, at a given iteration, we use the left point as an approximation to the zero point. c. When using the bisection method, we may sometimes find that there may be a zero on both sides of the midpoint. d. In cases where there is more than zero in an interval, the bisection method will find all the zeros. e. If there is exactly one zero in the starting interval [a,b], the bisection method will always converge to this zero a. (Mid-term 2006) We are trying to find the zeros of the function f (x) = (x 3)(x 2 3x + 2) using the bisection method. We start with the interval [a,b] = [0,3.5], perform 1000 iterations and let x denote the last estimate for the zero. What will the result be? x close to 2 No convergence x close to 2 x close to 1 b. We use the bisection method to find a zero of the function f (x) = cos(x) on the interval [0,10], where x is given in radians. Then the approximated solution will converge to π/2 3π/2 5π/2 The method will not converge c. (Mid-term 2005) We define a relative of the bisection method for solving the equation f (x) = 0, which we call the trisection method. Instead of dividing the interval into parts each time, we divide it into three equal parts and choose the subinterval where f has opposite signs at the s. If this occurs for several subintervals we choose the subinterval which is 199
200 furthest to the right on the real line. We start with the interval [0,1] and know that f is continuous and only has one root in this interval, but we do not know where the root is. Which is the smallest of the given number of iterations that we need to use to be certain that the trisection method gives an absolute error less than 10 12? The equation f (x) = x cos x = 0 has a zero at x a. Use the Bisection method to find an approximation to the zero, starting with [a,b] = [0,1]. How many correct digits do you have after ten steps? Svar: Approximation after 10 steps: b. How many steps do you need to get ten correct digits with the Bisection method? Svar: To get 10 correct digits it is common to demand that the relative error is smaller than , even though this does not always ensure that we have 10 correct digits. A challenge with the relative error is that it requires us to know the exact zero. In our case we have a very good approximation that we could use, but as we commented when we discussed properties of the relative error, it is sufficient to use a rough estimate, like 0.7 in this case. The required inequality is therefore 1 2 N This inequality can be easily solved and leads to N 35. c. Write a program that implements the Bisection method, and compute an approximation to the root with the number of iterations that you found in (b). How does the actual error compare with the requirement of ten correct digits? Svar: Actual error: d. Make sure you are using 64 bit floating-point numbers and do 60 iterations. Verfiy that the error does not improve after about 54 iterations. 200
201 333. Repeat exercise 332, but use the function f (x) = x 2 2 with a suitable starting interval that contains the root 2. The first 20 digits of this root are Apply the Bisection method to the function sin x on the interval [ 1,20] sufficiently many times to see which root is selected by the method in this case Mark each of the following statements as true or false. a. If we use the secant method on a function that has exactly one zero, the method will always converge. b. When the Secant method converges to a zero c with f (c) 0, the number of correct digits increases by about a factor of 1.62 per iteration (Exam 2010) You are to use the secant method to find the zero of x 3 2 and start with the initial values x 0 = 2 and x 1 = 2. After one step, what is the approximate zero x? x = 0.2 x = 0 x = 0.33 x = a. Find an equation which is zero at c = 3. Use the Secant method and determine an approximation to c with 2 correct digits by hand. Program the Secant method, and determine an approximation with 15 correct digits using the program. Svar: f (x) = x 2 3. One iteration gives the approximation which has two correct digits ( with 20 correct digits). After 6 iterations we obtain the approximation b. Repeat (a), but with c = 2 1/12. Svar: f (x) = x c. Repeat (a) but with c = e, where e = is the base for natural logarithms. Svar: f (x) = ln x In this exercise we are going to test the Secant method on the function f (x) = (x 1) 3 with the starting values x 0 = 0.5 and x 1 =
202 Løsningsforslag: For the function f (x) = (x 1) 3 the secant method gives x n 1 x n 2 x n = x n 1 f (x n 1 ) f (x n 2 ) f (x n 1) x n 1 x n 2 = x n 1 (x n 1 1) 3 (x n 2 1) 3 (x n 1 1) 3 x n 1 x n 2 = x n 1 (x n 1 1) 3 (x n 2 1) 3 (x n 1 1) 3 a. Perform 7 iterations with the Secant method, and compute the relative error at each iteration. Løsningsforslag: The first 7 iterations give b. How many correct digits are gained in each of the iterations, and how does this compare with observation??? Explain your answer. Løsningsforslag: We see that we still have a deviation bigger than 10 2 after all these iterations, so that we don t seem to get 62% new correct digits per iterations (we should at least obtain at least one new correct digit for every second iteration). This examples therefore does not agree with Observation??. But notice that f (1) = 0, so that we cannot find a γ as demanded by Theorem??. This is the reason why we do not observe the convergence speed noted in Observation?? Mark each of the following statements as true or false. a. If both the secant method and Newton s method converges, Newton s method will in general converge faster. b. Newton s method needs two initial values 202
203 340. a. (Mid-term 2007) We are discussing methods for finding solutions of the equation f (x) = 0, where f is a continuous function on the interval [a,b]. Which of the following statements are correct? If f (x) is a polynomial of degree 4 or higher, the zeros can only be found using numerical techniques. The bisection method gives a solution only if there is exactly one zero in [a,b]. The secant method can only be used when f (x) has different signs at x = a and x = b. If it works, Newton s method will converge faster than the bisection method. b. (Continuation exam 2010) We use Newton s method to find an approximation to the positive solution of x 2 = 3, with starting value x 0 = 1. Then x 2 is given by x 2 = 1 x 2 = 2 x 2 = 9/4 x 2 = 7/4 c. (Mid-term 2004) We apply Newton s method x n+1 to the function f (x) = x 2 A where A is a positive, real number. If we denote the error by e n = x n A, we have e n+1 = e n 2x n e n+1 = e2 n 2x n e n+1 = e2 n xn 2 e n+1 = e ne n 1 x n d. (Exam 2008) We have a function f (x) and we are going to find a numerical approximation to the solution of the equation f (x) = 0. Then one of the following statements are true: The secant method demands that f (x) is known. The secant method will usually converge faster than Newton s method. Newton s method will converge for all functions f. Newton s method will usually converge faster than the bisection method. 203
204 341. Perform 7 iterations with Newton s method with the function f (x) = 1 ln x which has the root x = e, starting with x 0 = 3. How many correct digits are there in the final approximation? Svar: If you do the computations with 64-bit floating-point numbers, you have full machine accuracy after just 4 iterations. If you do 7 iterations you actually have about 164 correct digits In this exercise we are going to test the three numerical methods that are discussed in this chapter. We use the equation f (x) = sin x = 0, and want to compute the zero x = π a. Determine an approximation to π by performing ten manual steps with the Bisecton method, starting with the interval [3, 4]. Compute the error in each step by comparing with the exact value. Svar: Midpoint after 10 iterations: b. Determine an approximation by performing four steps with the Secant method with starting values x 0 = 4 and x 1 = 3. Compute the error in each step. Svar: Approximation after 4 iterations: c. Determine an approximation by performing four steps with Newton s method with initial value x 0 = 3. Compute the error in each step. Svar: Approximation after 4 iterations: d. Compare the errors for the three methods. Which one converges the fastest? 343. Some computers do not have hardware for division, and need to compute numbers like 1/R in some other way. a. Set f (x) = 1/x R. Verify that the Newton iteration for this function is x n+1 = x n (2 Rx n ), and explain how this can be used to compute 1/R without division. Løsningsforslag: We have that f (x) = 1/x 2, so that the Newton iteration is x n+1 = x n f (x n) f (x n ) = x n 1/x n R 1/(x n ) 2 = x n + x n R(x n ) 2 = x n (2 Rx n ). 204
205 In this formula we do not need to perform division, only multiplication. By iterating this formula we can therefore approximate 1/R by only applying multiplications. b. Use the idea in (a) to compute 1/7 with an accuracy of ten decimal digits. Svar: After 5 iterations we have the approximation in which all the digits are correct (the fourth approximation has approximate error ). The code can look as follows: N=30 epsilon=10**(-10) i=0 xp=z=0.1 R=7.0 abserr=abs(z) while i <= N and abserr >= epsilon*abs(z): z=xp*(2.0-r*xp) print i,z abserr=abs(z-xp) xp=z i=i Suppose that you are working with a function f where both f, f andf are continuous on all of R. Suppose also that f has a zero at c, that f (c) 0 and that Newton s method generates a sequence {x n } that converges to c. From lemma?? we know that the error e n = x n c satisfies the relation e n+1 = 1 2 f (ξ n ) f (x n ) e2 n for n 0, (8) where ξ n is a number in the interval (c, x n ) (or the interval (x n,c) if x n < c). a. Use 8 to show that if f (c) 0, there exists an N such that either x n > c for all n > N or x n < c for all n > N. (Hint: Use the fact that {x n } converges to c and that neither f nor f changes sign in sufficiently small intervals around c.) b. Suppose that f (c) > 0, but that f (c) = 0 and that the sign of f changes from positive to negative at c (when we move from left to right). Show that there exists an N such that (x n+1 z)(x n z) < 0 for all n > N. In other words, the approximations x n will alternately lie to the left and right of c when n becomes sufficiently large. 205
206 c. Find examples that illustrate each of the three types of convergence found in (a) and (b), and verify that the behaviour is as expected by performing the computations (with a computer program). Svar: An example where x n > c for n > 0 is f (x) = x 2 2 with c = 2 (choose for example x 0 = 1). If we use the same equation, but choose x 0 = 1, we converge to 2 and have x n < c for large n (in fact n > 0). An example where the iterations jump around is in computing an approximation to a zero of f (x) = sin x, for example with x 0 = 4 (convergence to c = π) Mark each of the following statements as true or false. a. When we use the approximation f (a) (f (a +h) f (a))/h on a computer, we can always obtain higher accuracy by choosing a smaller value for h. b. If we increase the number of bits for storing floating-point numbers (e.g.128-bit precision), we can obtain better numerical approximations to derivatives. c. We are using Newton s difference quotient method to approximate the derivative of the function f (x) = e x at the point x = 1 with a step value of h = 0.1 (with 64-bit precission). If we change the step length to h = 0.01 then the error will be reduced by approximately a factor of 10. d. The approximation f (a) (f (a + h) f (a))/h will give the exact answer (ignoring numerical round-off errors) if the function f is linear. e. Since we cannot know exactly how well the values of f (a +h) and f (a) are represented on a computer, it is difficult to estimate accurately what the error will be in numerical differentiation a. (Exam 2010) We are to calculate an approximation to the derivative f (a) to the function f (x) = cos(x) by the approximation f (a) f (a + h) f (a). h Then the absolute error for any h > 0 is bounded by (we do not take round off errors into account) h 2 /2 206
207 h 2 cos(1) h cos(a)/4 h/2 b. (Exam 2008) We are going to calculate an approximation to the derivative f (a) of the function f by the approximation f f (a + h) f (a) (a). h If we are using floating point numbers the total error is bounded by (In the two last alternatives ɛ deps on the type of floating point numbers used): h2 2 max x [a,a+h] f (x) h3 6 max x [a,a+h] f (x) f (x) + 6ɛ max x [a,a+h] f (x) h2 6 max x [a,a+h] h 2 max x [a,a+h] f (x) + 2ɛ h h 3 max x [a,a+h] f (x) 347. In this exercise we are going to numerically compute the derivative of f (x) = e x at a = 1 using Newton s quotient as described in observation??. The exact derivative to 20 digits is f (1) a. Compute the approximation ( f (1+h) f (1) ) /h to f (1). Start with h = 10 4, and then gradually reduce h. Also compute the error, and determine an h that gives close to minimal error. Løsningsforslag: On my computer 10 8 is the power of 10 which gives the least error in the approximation. This can be btained by running the following program: from math import * for p in range(15): h=10.0**(-p) print p, abs((exp(1+h)-exp(1))/h-exp(1)) b. Determine the optimal h as described in Lemma?? and compare with the value you found in (a). 207
208 Svar: h Løsningsforslag: If we use the values ɛ = from Example??, then Lemma?? gives the optimal h h = 2 ɛ (terms cancel since f (a) = f (a)) Mark each of the following statements as true or false. a. If we ignore round-off errors, the symmetric Newton s quotient method is exact for polynomials of degree 2 or lower. b. Even though the symmetric Newton differentiation scheme gives better accuracy, there is a trade-off as it is much more computationally demanding (i.e. it requires many more calculations) than the non-symmetric method In this exercise we are going to check the symmetric Newton s quotient and numerically compute the derivative of f (x) = e x at a = 1, see exercise Recall that the exact derivative with 20 correct digits is f (1) a. Compute the approximation ( f (1 + h) f (1 h) ) /(2h) to f (1). Start with h = 10 3, and then gradually reduce h. Also compute the error, and determine an h that gives close to minimal error. b. Determine the optimal h given by (??) and compare with the value you found in (a). Svar: h Determine f (a) numerically using the two asymmetric Newton s quotients f (a + h) f (a) f (a) f (a h) f r (x) =, f l (x) = h h as well as the symmetric Newton s quotient. Also compute and compare the relative errors in each case. a. f (x) = x 2 ; a = 2; h = b. f (x) = sin x; a = π/3; h = 0.1. Svar: With 6 digits: (f (a + h) f (a))/h = , relative error: (f (a) f (a h))/h = , relative error: ( f (a + h) f (a h))/(2h) = , relative error:
209 c. f (x) = sin x; a = π/3; h = d. f (x) = sin x; a = π/3; h = e. f (x) = 2 x ; a = 1; h = f. f (x) = x cos x; a = π/3; h = a. Show that the approximation to f (a) given by the symmetric Newton s quotient is the average of the two asymmetric quotients f r (x) = f (a + h) f (a), f l (x) = h f (a) f (a h). h b. Sketch the graph of the function f (x) = x2 + 10x 5 4 on the interval [0, 6] together with the three secants associated with the three approximations to the derivative in (a) (use a = 3 and h = 2). Can you from this judge which approximation is best? Løsningsforslag: We can plot the cuve together with the secants as follows with Python: from numpy import * from scitools.easyviz import * x=arange(0,6,0.05,float) plot(x,(-x**2+10*x-5)/4) hold( on ) plot([1,3],[(-1**2+10*1-5)/4,(-3**2+10*3-5)/4]) plot([1,5],[(-1**2+10*1-5)/4,(-5**2+10*5-5)/4]) plot([3,5],[(-3**2+10*3-5)/4,(-5**2+10*5-5)/4]) c. Determine the three difference quotients in (a) numerically for the function f (x) using a = 3 and h 1 = 0.1 and h 2 = What are the relative errors? Svar: With 6 digits: (f (a + h) f (a))/h = 0.975, relative error: (f (a) f (a h))/h = 1.025, relative error: (f (a + h) f (a h))/(2h) = 1, relative error:
210 d. Show that the symmetric Newton s quotient at x = a for a quadratic function f (x) = ax 2 + bx + c is equal to the derivative f (a) Use the symmetric Newton s quotient and determine an approximation to the derivative f (a) in each case below. Use the values of h given by h = 10 k k = 4,5,...,12 and compare the relative errors. Which of these values of h gives the smallest error? Compare with the optimal h predicted by (??). a. The function f (x) = 1/(1 + cos(x 2 )) at the point a = π/4. Svar: Optimal h: b. The function f (x) = x 3 + x + 1 at the point a = 0. Svar: Optimal h: Mark each of the following statements as true or false. a. The 4-point method with a step length of h = 0.2 will usually have a smaller error than the symmetric Newton s quotient method with h = 0.1. b. If we ignore round-off, the 4-point method is exact for all polynomials In this exercise we are going to check the 4-point method and numerically compute the derivative of f (x) = e x at a = 1. For comparison, the exact derivative to 20 digits is f (1) a. Compute the approximation f (a 2h) 8f (a h) + 8f (a + h) f (a + 2h) 12h to f (1). Start with h = 10 3, and then gradually reduce h. Also compute the error, and determine an h that gives close to minimal error. Løsningsforslag: On my computer 10 3 is the power of 10 which gives the least error in the approximation. This can be tested by running the following program: from math import * for p in range(15): h=10.0**(-p) print p, abs((exp(1-2*h)-8*exp(1-h)+8*exp(1+h)-exp(1+2*h))/(12*h)-exp(1)) 210
211 b. Determine the optimal h given by (??) and compare with the experimental value you found in (a). Svar: Opitmal h: Løsningsforslag: If we use the value ɛ = from Example?? then (??) gives the optimal h h = 5 27ɛ (terms cancel since f (a) = f (5) (a)) 355. a. (Exam 2009) We use the expression (f (h) 2f (0) + f (h))/h 2 to calculate approximations to f (0) (we do the calculations exact, without round off errors). Then the result will always be correct if f (x) is a trigonometric function a logarithmic function a polynomial of degree 4 a polynomial of degree 3 b. (Exam 2007) We approximate the second derivative of the function f (x) at x = 0, by the approximation D 2 f (0) = f (h) 2f (0) + f ( h) h 2 We assume that f is differentiable an infinite number of times, and we do not take round off errors into account. Then the error is bounded by h2 12 max x [ h,h] f (x) h2 48 max x [ h,h] f (4) (x) h 4 max x [ h,h] f (x) f (4) (x) h2 12 max x [ h,h] f (0) D 2 f (0) 356. We use our standard example f (x) = e x and a = 1 to check the 3-point approximation to the second derivative given in (??). For comparison recall that the exact second derivative to 20 digits is f (1)
212 a. Compute the approximation ( f (a h) 2f (a) + f (a + h) ) /h 2 to f (1). Start with h = 10 3, and then gradually reduce h. Also compute the actual error, and determine an h that gives close to minimal error. Løsningsforslag: On my computer 10 4 is the power of 10 which gives the least error in the approximation. This can be tested by running the following program: from math import * for p in range(15): h=10.0**(-p) print p, abs((exp(1-h)-2*exp(1)+exp(1+h))/h**2-exp(1)) b. Determine the optimal h given by (??) and compare with the value you determined in (a). Svar: Optimal h: Løsningsforslag: If we use the value ɛ = from Example?? then Observation?? gives the optimal choice of h h = 4 36ɛ (terms cancel since f (a) = f (4) (a)) This exercise illustrates a different approach to designing numerical differentiation methods. a. Suppose that we want to derive a method for approximating the derivative of f at a which has the form f (a) c 1 f (a h) + c 2 f (a + h), c 1,c 2 R. We want the method to be exact when f (x) = 1 and f (x) = x. Use these conditions to determine c 1 and c 2. Svar: c 1 = 1/(2h), c 2 = 1/(2h). Løsningsforslag: If the approximation method f (a) c 1 f (a h)+c 2 f (a+ h) is to be exact for f (x) = 1, we must have that 0 = c 1 +c 2, since f (a h) = f (a + h) = 1, and since f (x) = 0. Therefore we must have that c 2 = c 1. If the method is to be exact for f (x) = x we must in the same way have that 1 = c 1 (a h) + c 2 (a + h) = c 1 (a h) c 1 (a + h) = 2c 1 h, so that c 1 = 1 2h,so that also c 2 = 1 1 2h. The method therefore becomes h) + 1 2h f (a + h) = f (a+h) f (a h) 2h 212 2h f (a
213 b. Show that the method in (a) is exact for all polynomials of degree 1, and compare it to the methods we have discussed in this chapter. Løsningsforslag: If f (x) = cx + d we have that f (x) = c, and the method takes the form f (a + h) f (a h) c(a + h) + d (c(a h) + d) = 2h 2h = 2ch 2h = c, so that the method is exact for all polynomials of degree 1.We see that the method coincides with the symmetric Newton-method for differentiation, and it therefore has an error of order 1, which is better than the h 2 Newton s quotient (which has an error of order 1 h ). It is worse than the four point method for numerical differentiation,which has order 1. h 4 Here it also should have been mentioned that the method also is exact for polynomials of degree 2 (also see 351). There are several ways to see this. First, the error estimate from Section?? uses f (3) (x), and since all second degree polynomials have a third derivative equal to 0, the error must be zero. One could also as above substitute f (x) = x 2 into the formula: f (a + h) f (a h) 2h = (a + h)2 (a h) 2 2h = 4ah 2h = 2a, which also is f (a). Finally, the symmetric Newton quotient was defined as the derivativee at a of the unique parabola interpolating f at a h, a, and a+h. If f itself is a parabola it is equal to this interpolant since it is unique, so that the symmetric Newton quotient must return the derivative. c. Use the procedure in (a) and (b) to derive a method for approximating the second derivative of f, f (a) c 1 f (a h) + c 2 f (a) + c 3 f (a + h), c 1,c 2,c 3 R, by requiring that the method should be exact when f (x) = 1, x and x 2. Do you recognise the method? Svar: c 1 = 1/h 2, c 2 = 2/h 2, c 3 = 1/h 2. Løsningsforslag: If the approximation method f (a) c 1 f (a h)+c 2 f (a)+ c 3 f (a + h) is exact for f (x) = 1, we must have that 0 = c 1 + c 2 + c 3. If it is exact for f (x) = x we must have that 0 = c 1 (a h) + c 2 a + c 3 (a + h) = a(c 1 + c 2 + c 3 ) + h( c 1 + c 3 ) = h( c 1 + c 3 ), which gives that c 1 = c 3. If it is exact for f (x) = x 2 we must have that 2 = c 1 (a h) 2 + c 2 a 2 + c 3 (a + h) 2 = a 2 (c 1 + c 2 + c 3 ) 2ahc 1 + 2ahc 3 + h 2 (c 1 + c 3 ) = 2c 1 h 2, 213
214 which gives that c 1 = 1 h 2. We therefore also get that c 3 = 1 h 2, and that c 2 = c 1 c 2 = 2 h 2, so that the method becomes 1 2h f (a h) 1 h f (a) + 1 f (a h) 2f (a) + f (a + h) f (a + h) = 2h h 2. We see that this coincides with the already seen three point method to compute the second derivative in this section. d. Show that the method in (c) is exact for all cubic polynomials. Løsningsforslag: All third degree polynomials have a fourth derivative equal to 0, and therefore the truncation error becomes 0 (M 1 = 0 in Theorem??). Alternatively we can substitute f (x) = x 3 into the formula: f (a h) 2f (a) + f (a + h) 2h = (a h)3 2a 3 + (a + h) 3 h 2 = a3 3a 2 h + 3ah 2 h 3 2a 3 + a 3 + 3a 2 h + 3ah 2 + h 3 h 2 = 6ah2 h 2 = 6a, which coincides with the second derivative of f in a Previously we saw the that the Newton difference quotient could be applied reduce bass in digital sound. What will happen to the sound if we instead apply the numerical approximation of the second derivative to it? Løsningsforslag: We see that the coefficients in the new approximation are taken from row 2 of Pascal s triangle with alternating sign. This means that also this approximation reduces bass. Since the values are taken from a higher row in Pascal s triangle, one is lead to believe that it reduces more bass than the Newton difference quotient Assume that x 0, x 1,..., x k is a uniform partition of [a,b]. It is possible to show that the divided difference f [x 0, x 1,..., x k ] can be written on the form a k r =0 c r ( 1) r f (x r ), where a is a constant and c r are taken from row k 1 in Pascal s triangle. By following the same reasoning as in this section, or appealing to Theorem??, it is also clear that higher order divided differences are approximations to the higher order derivatives. Explain why this means that applying approximations to the higher order derivatives to sound samples in a sound will typically reduce bass in sound. 214
215 360. Mark each of the following statements as true or false. a. Numerical integration methods are usually constructed by dividing the interval of integration into many subintervals and using some sort of approximation to the area under the function on each subinterval In this exercise we are going to study the definition of the integral for the function f (x) = e x on the interval [0,1]. a. Determine lower and upper sums for a uniform partition consisting of 10 subintervals. Svar: I , I b. Determine the absolute and relative errors of the sums in (a) compared to the exact value e 1 = of the integral. Svar: I I I I 0.085, I = I I I I 0.087, I = c. Write a program for calculating the lower and upper sums in this example. How many subintervals are needed to achieve an absolute error less than ? 362. Mark each of the following statements as true or false. a. When we use the midpoint rule for numerical integration, round-off errors due to subtraction of two similar numbers is a major source of errors. b. The midpoint rule gives the exact result for polynomials of degree 1. c. The midpoint rule gives the exact result for polynomials of degree 2. d. The global error in the midpoint method is one order lower than the local error. e. When we decrease the step length h in the midpoint rule by a factor of 3, the error is reduced by roughly a factor of We use the midpoint rule to approximate the integral 1 0 x 2 dx 215
216 using the midpoint rule with 2 subintervals. What is the result? 5/16 1/4 4/9 2/5 Svar: 5/16. Løsningsforslag: We get that I mid = 1 2 f (1/4) f (3/4) = = = 5 16, so that the first alternative is correct Calculate an approximation to the integral π/2 0 sin x dx = x2 with the midpoint rule. Split the interval into 6 subintervals. Svar: Approximation: (with 6 digits) Mark each of the following statements as true or false. a. The trapezoidal rule is usually more accurate than the midpoint rule. b. Because every point of measurement in the trapezoidal rule is used in two different subintervals, we must evaluate the function we want to integrate twice at every point We use the trapezoidal rule to approximate the integral 1 0 x 2 dx using the trapezoidal rule with 2 subintervals. What is the result? 1/2 3/8 5/9 3/5 Svar: 3/8 Løsningsforslag: We have that I tr ap = 1 ( ( )) f (0) + f (1) 1 + f = 1 ( ) = 3 4 8, so that the second alternative is correct. 216
217 367. Calculate an approximation to the integral π/2 0 sin x dx = x2 with the trapezoidal rule. Split the interval into 6 subintervals. Svar: Approximation: (with 6 digits) In this exercise you are going to program an algorithm like algorithm?? for the trapezoidal rule. If you cannot program, use the trapezoidal rule manually with 10 subintervals, check the error, and skip the second part of (b). a. Write a program that implements the midpoint rule as in algorithm?? and test it on the integral 1 0 e x dx = e 1. Svar: Approximation with 10 subintervals: (with 6 digits). b. Determine a value of h that guarantees that the absolute error is smaller than Run your program and check what the actual error is for this value of h. (You may have to adjust algorithm?? slightly and print the absolute error.) Svar: h When h is halved in the trapezoidal rule, some of the function values used with step length h/2 are the same as those used for step length h. Derive a formula for the trapezoidal rule with step length h/2 that makes it easy to avoid recomputing the function values that were computed on the previous level Mark each of the following statements as true or false. a. Simpson s rule requires that we use an odd number of measurement points. b. Simpson s rule is exact for polynomials of degree 3 or lower a. (Exam 2010) Which of the integration method (trapezoidal, midpoint and Simpson s) will be most accurate for a polynomial of degree 1? Just the trapezoidal rule. Just Simpson s rule. Just the midpoint rule. All will be equally accurate. 217
218 b. (Continuation exam 2009) We use Simpson s method to calculate approximations to b a f (x)dx (We do not take round off errors into account). Then the result will always be correct if f (x) is a trigonometric function. a logarithmic function. a polynomial of degree 2 on the form g (x)/h(x) where f and g are polynomials of degree 2. c. (Exam 2008) The midpoint rule evaluates the integral of f on the interval [a,b] by the approximation b a f (x)dx (b a)f ((a + b)/2). Which of the following statements are true (we do not take round off errors into account)? The midpoint rule is more accurate than Simpson s rule. The midpoint rule and the trapezoidal rule always give the exact same error. The midpoint rule only gives 0 error if f (x) = c for som arbitrary constant c. The midpoint rule gives 0 error if f (x) is an arbitrary straight line in the x, y-plane Calculate an approximation to the integral π/2 0 sin x dx = x2 with Simpson s rule. Split the interval into 6 subintervals. Svar: Approximation: (with 6 digits) a. How many function evaluations do you need to calculate the integral 1 dx x with the trapezoidal rule to make sure that the error is smaller than Svar: evaluations. 218
219 Løsningsforslag: Since the error in the trapezoidal rule is bounded by (b a) h2 6 max x [a,b] f (x), and since f 8 (x) = (which attains maximum (1+2x) 3 absolute value for x = 0), we need to choose h so that (b a) h2 6 max x [a,b] f (x) = 8 h , which gives that h /2. The number of function evaluations is then 1/h = / , which means that at least evaluations are needed. b. How many function evaluations are necessary to achieve the same accuracy with the midpoint rule? Svar: evaluations. Løsningsforslag: Since the error in the midpoint rule is bounded by (b a) h2 24 max x [a,b] f (x), we obtain as in (a) that (b a) h2 24 max x [a,b] f (x) = 2 h , which gives that h The number of function evaluations is then 1/h = 10 5 / , which means that at least evaluations are needed. c. How many function evaluations are necessary to achieve the same accuracy with Simpson s rule? Svar: 383 evaluations. Løsningsforslag: Since the error in Simpson s rule is bounded by (b a) h4 180 max x [a,b] f (i v) (x), and since f (i v) (x) = 384 (which attains maximum absolute value for x = 0), we need to choose h so (1+2x) 5 that (b a) h4 180 max x [a,b] f (i v) (x) = 384 h , which gives that h ( /384) 1/4. The number of function evaluations is then 1/h = ( /384) 1/ , which means that at least 383 evaluations are needed In this exercise you are going to program an algorithm like algorithm?? for Simpson s rule. If you cannot program, use Simpson s rule manually with 10 subintervals, check the error, and skip the second part of (b). 219
220 a. Write a program that implements Simpson s rule as in algorithm?? and test it on the integral 1 0 e x dx = e 1. Svar: Approximation with 10 subintervals: (with 10 digits). b. Determine a value of h that guarantees that the absolute error is smaller than Run your program and check what the actual error is for this value of h. (You may have to adjust algorithm?? slightly and print the absolute error.) Svar: h a. Verify that Simpson s rule is exact when f (x) = x i for i = 0, 1, 2, 3. Løsningsforslag: It is enough to verify Simpson s rule on each interval. The integrals become a+h a h a+h a h a+h a h a+h a h x 3 dx = 1 4 ((a + h)4 (a h) 4 ) = 1 4 (8a3 h + 8ah 3 ) = 2a 3 h + 2ah 3 x 2 dx = 1 3 ((a + h)3 (a h) 3 ) = 1 3 (6a2 h + 2h 3 ) = h 3 (6a2 + 2h 2 ) xdx = 1 2 ((a + h)2 (a h) 2 ) = 1 4ah = 2ah 2 dx = 2h. We also get that the rule itself becomes h 3 ((a h)3 + 4a 3 + (a + h) 3 ) = h 3 (6a3 + 6ah 2 ) = 2a 3 h + 2ah 3 h 3 ((a h)2 + 4a 2 + (a + h) 2 ) = h 3 (6a2 + 2h 2 ) h ((a h) + 4a + (a + h)) = 2ah 3 h ( ) = 2h. 3 This shows that Simpsons rule is exact for the given polynomials. b. Use (a) to show that Simpson s rule is exact for any cubic polynomial. Løsningsforslag: For f (x) = bx 3 + cx 2 + dx + e the integral is a+h a h f (x)dx = b a+h a h x 3 dx + c a+h 220 a h x 2 dx + d a+h a h xdx + e a+h a h 1dx.
221 The rule itself now gives h (f (a h) + 4f (a) + f (a + h)) 3 = b h 3 ((a h)3 + 4a 3 + (a + h) 3 ) + c h 3 ((a h)2 + 4a 2 + (a + h) 2 ) + d h 3 ((a h) + 4a + (a + h)) + e h ( ) 3 We see that equality follows from that we have equality for x 3, x 2, x,1. c. Could you reach the same conclusion as in (b) by just considering the error estimate (??)? Løsningsforslag: Since f (4) (x) = 0 for all x for every third degree polynomial, it follows directly from the error estimate that the method is exact for such functions We want to design a numerical integration method b a f (x)dx w 1 f (a) + w 2 f (a 1/2 ) + w 3 f (b). Determine the unknown coefficients w 1, w 2, and w 3 by demanding that the integration method should be exact for the three polynomials f (x) = x i for i = 0, 1, 2. Do you recognise the method? Svar: w 1 = w 3 = (b a)/6, w 2 = 2(b a)/ a. (Continuation Exam 2009) We have the differential equation y + r y = r 2 x with initial value y(0) = 1, where r is an arbitrary real number. The solution is given by e r x 1 r 2 x 1 + r x 1 r x b. (Exam 2010) We are to solve differential equations numerically. For three of the equations below we may encounter major problems if we choose unfortunate starting values for x and t. Which equation will never give such problems? x x = 1 x = e t
222 x = t + ln x x = t/(x 2) 378. What features of the following differential equations could cause problems if you try to solve them? a. x = t/(1 x). Svar: x(t) = 1 will cause problems. b. x = x/(1 t). Svar: The differential equation is not defined for t = 1. c. x = ln x. Svar: The equation is not defined when x(t) is negative. d. x x = 1. Svar: The equation does not hold if x (t) = 0 or x(t) = 0 for some t. e. x = arcsin x. Svar: The equation is not defined for x(t) > 1. f. x = 1 x 2. Svar: The equation is not defined for x(t) > Mark each of the following statements as true or false. a. Euler s method gives the values of the exact solution at all the points x 0, x 1,..., x n if the differential equation is linear. b. In Euler s method it is assumed that the solution is a straight line between each calculated point We have the differential equation x = 1 x 2, x(0) = 0 and want to approximate the value of x(0.1) by using a single step with Euler s method. What will the approximated value be? x(0.1) = 1/10 x(0.1) = 1 1/2 1/ Use Euler s method with three steps with h = 0.1 on your calculator to compute approximate solutions of the following differential equations: 222
223 a. x = t + x, x(0) = 1. Svar: x(0.3) Løsningsforslag: We get that x 1 = x 0 + h f (t 0, x 0 ) = f (0,1) = (0 + 1) = 1.1 x 2 = x 1 + h f (t 1, x 1 ) = f (0.1,1.1) = ( ) = 1.22 x 3 = x 2 + h f (t 2, x 2 ) = f (0.2,1.22) = ( ) = b. x = cos x, x(0) = 0. Svar: x(0.3) c. x = t/(1 + x 2 ), x(0) = 1. Svar: x(0.3) d. x = 1/x, x(1) = 1. Svar: x(1.3) e. x = 1 x 2, x(0) = 0. Svar: x(0.3) Write a program that implements Euler s method for first order differential equations in the form x = f (t, x), x(a) = x 0, on the interval [a,b], with n time steps. You may assume that the function f and the numbers a, b, x 0, and n are given. Test the program on the equation x = x with x(0) = 1 on the interval [0,1]. Plot the exact solution x(t) = e t alongside the approximation and experiment with different values of n Suppose we have the differential equation x = f (t, x), x(b) = x 0, and we seek a solution on the interval [a,b] where a < b. Adjust algorithm?? so that it works in this alternative setting where the initial value is at the right of the interval. Løsningsforslag: The code can be changed as follows: h = (b a)/n; t 0 = b; for k = 0, 1,..., n 1 x k+1 = x k h f (t k, x k ); t k+1 = b (k + 1)h; 223
224 Here we simply have used Euler s method with negative step size Recall that a common approximation to the derivative of x is given by x x(t + h) x(t) (t). h Derive Euler s method by rewriting this and making use of the differential equation x (t) = f ( t, x(t) ). Løsningsforslag: If we insert x (t) = f (t, x(t)) in the approximation we get that f (t, x) x(t+h) x(t) h, which can be written x(t + h) x(t) h f (t, x(t)), which means that x(t + h) x(t) + h f (t, x(t)). The right hand side here is equivalent to one step with Euler s method Mark each of the following statements as true or false. a. The order of the global error in Euler s method is one lower than the order of the local error. b. Round-off errors is a major source of error when we use Euler s method to solve differential equations numerically. c. When we decrease the step length h in Euler s method from 0.2 to 0.1, the local error will be reduced by a factor of roughly Suppose we perform one step of Euler s method for the differential equation x = sin x, x(0) = 1. Find an upper bound for the absolute error. Svar: R 1 (h) h2 4. Løsningsforslag: If the step length is h, we obtain the approximation The error is given by x(h) x(0) + h f (t, x) = 1 + h sinh. R 1 (h) = h2 2 x (ξ) where ξ (0,h). Since x (t) = sin x(t), we have x (t) = x (t)cos x(t) = sin x(t)cos x(t) = sin( 2x(t) ) 224 2
225 We therefore have x (t) 1/2, so R 1 (h) h Mark each of the following statements as true or false. a. The quadratic Taylor method will give exact values in the calculated points if the solution of the differential equation is a polynomial of degree 2 or lower. b. Arbitrarily accurate methods can be obtained by using higher order Taylor methods, provided higher order derivatives are calculated correctly Compute numerical solutions to x(1) for the equations below using two steps with Euler s method, the quadratic Taylor method and the quartic Taylor method. For comparison the correct solution to 14 decimal digits is given in each case. a. x = t 5 + 4, x(0) = 1, x(1) = 31/ Svar: Euler: x(1) Quadratic Taylor: x(t) Quartic Taylor: x(t) b. x = x + t, x(0) = 1, x(1) Svar: Euler: x(1) 2.5. Quadratic Taylor: x(t) Quartic Taylor: x(t) c. x = x + t 3 3(t 2 + 1) sin t + cos t, x(0) = 7, x(1) Svar: Euler: x(1) Quadratic Taylor: x(t) Quartic Taylor: x(t) We are given the differential equation x = e t 2, x(0) = 0. Compute an estimate of x(0.5) by taking one step with each of the methods below, and find an upper bound on the absolute error in each case. 225
226 a. Euler s method. Svar: Euler: x(0.5) 1.5. Since we only take one step, Euler s method is just the approximation x(h) x(0) + hx (0) where h = 0.5, x(0) = 1, and x (t) = e t 2. The error is therefore given by the remainder in Taylor s formula R 1 (h) = h2 2 x (ξ 1 ), where ξ 1 (0,h). Since the right-hand side g (t) = e t 2 of the differential equation is indepent of x, we simply have x (t) = d dt ( x (t) ) = d dt ( g (t) ) = d dt ( e t 2) = 2te t 2. To bound the absolute error R 1 (h), we therefore need to bound the absolute value of this expression. A simple upper bound is obtained by using the estimates t 0.5 and e t 2 1, R 1 (0.5) = 1 16 = The actual error turns out to be about b. The quadratic Taylor method. Svar: Quadratic Taylor: x(0.5) 1.5. In this case we need to estimate R 2 (0.5), where R 2 (h) = h3 6 x (ξ 2 ) and ξ 2 (0,h). We have x (t) = g (t) = 2(2t 2 1)e t 2. The maximum of the first factor is 2 on the interval [0,0.5] and the maximum of the second factor is 1. We therefore have R 2 (0.5)
227 c. The cubic Taylor method. Svar: Cubic Taylor: x(0.5) In this case the remainder is R 3 (h) = h4 24 x (ξ 3 ), where ξ 3 (0,h) and x (t) = g (t) = 4t(3 2t 2 )e t 2. The quick estimate is 4t 2, 3 2t 2 3, e t 2 1 which leads to R 3 (0.5) = The true error is approximately We can improve the estimate slightly by finding the maximum of g (t). On the interval [0,0.5] this is an increasing function so its maximum is g (0.5) This leads to the slightly better estimate R 3 (0.5) In this exercise we are going to derive the quartic (degree four) Taylor method and use it to solve the equation for radioactive decay in exercise 397. a. Derive the quartic Taylor method. b. Use the quartic Taylor method to find the concentration of RN-222 in the 300 atoms per ml sample after 6 days using 3 time steps and compare your results with those produced by the quadratic Taylor method in exercise 398. How much has the solution improved (in terms of absolute and relative errors)? c. How many time steps would you have to use in the two Taylor methods to achive a relative error smaller than 10 5? d. What order would the Taylor order have to be to make sure that the relative error is smaller than 10 5 with only 3 steps? 391. In this exercise we are going to solve the differential equation x = f (t, x) = t 2 + x 3 x, x(0) = 1 (9) numerically with the quadratic Taylor method. 227
228 a. Find a formula for x (t) by differentiating equation 9. Svar: x (t) = 2t + (3x 2 1)x (t). Løsningsforslag: We get that x (t) = 2t + 3x 2 x (t) x (t) = 2t + (3x 2 1)x (t), where we substitute t 2 + x 3 x for x. b. Use the quadratic Taylor method and your result from a) to find an approximation to x(1) using 1, 2 and, 5 steps. Svar: Quadratic Taylor with 1 step: x(1) 1. Quadratic Taylor with 2 steps: x(1) 4. Quadratic Taylor with 5 steps: x(1) Løsningsforslag: One step with the quadratic Taylor method here becomes x k+1 = x k + hx k + h2 2 (2t k + (3x 2 k 1)x k ) where x k = t 2 k + x3 k x k. Since x 0 = = 0, one step with the quadratic Taylor method therefore gives x 1 = 1. The first step with the quadratic Taylor method clearly gives x 1 = 1, no matter what h is. If we use more steps the next step becomes x 1 = t x3 1 x 1 = t 2 1 x 2 = x 1 + ht h2 2 (2t 1 + (3x 2 1 1)t 2 1 ) = 1 + ht h2 2 (2t 1 + 2t 2 1 ) If h = 0.5 we get that x 2 = ( ) = = If h = 0.2 we get in the same way that the next steps give x 2 = , x 3 = , x 4 = , x 5 = c. Write a computer program that implements the quadratic Taylor method and uses it to find an approximation of x(1) with 10, 100 and 1000 steps. Svar: Quadratic Taylor with 10 steps: x(2) Quadratic Taylor with 100 or 1000 steps leads to overflow. Løsningsforslag: The code can look as follows: for N in [10,100,1000]: xk=1 tk=0 h=1.0/n 228
229 for k in range(n): xder=tk**2+xk**3-xk xk=xk+h*xder + (h**2/2)*(2*tk+(3*xk**2-1)*xder) tk=tk+h print xk If we run the code we get the approximation x(1) If we substitute N with 100 or 1000 we get instead the approximations , and In this exercise we are going to derive the cubic Taylor method and use it for solving equation (9) in exercise 391. a. Derive a general algorithm for the cubic Taylor method. b. Find a formula for x (t) by differentiating equation 9, and find an approximation to x(1) using 1 time step with the cubic Taylor method. Repeat using 2 time steps. Svar: x (t) = 2 + 6xx 2 + 3x 2 x x. One time step: x(2) Two time steps: x(2) c. How do the results from the cubic Taylor method compare with the results from the quadratic Taylor method obtained in exercise 391? d. Implement the cubic Taylor method in a program and compute an approximation to x(2) with 10, 100 and 1000 steps. Svar: 10 time steps: x(2) (overflow with 64 bit numbers). 100 time steps: overflow time steps: overflow a. (Continuation exam 2009) Which of the following statements is true? When solving differential equations numerically, round-off errors are never a problem. When doing numerical differentiation, round off errors are never a problem. When solving differential equations numerically, Euler s method is usually less accurate than the 4th order Runge-Kutta method. When doing numerical integration, the trapezoidal rule is usually more accurate than Simson s rule. 229
230 b. (Exam 2009) Which of the following statements is true? When solving differential equations numerically, Euler s method is usually more accurate than Euler s midpoint method. When solving differential equations numerically, Taylor s method of third order is usually more accurate than Euler s method. When solving differential equations numerically, Euler s method is usually more accurate than Taylor s method of second order. When numerical integration, the trapezoidal rule is usually more accurate than Simpson s rule. c. (Continuation exam 2007) Which of the following statements is true? The bisection method is a method for solving differential equations numerically. Round-off errors never create problems when solving differential equations numerically. Difference equations is a special case of differential equations The 4th order Runge Kutta method is more accurate than Euler s method Consider the first order differential equation x = x, x(0) = 1. a. Estimate x(1) by using one step with Euler s method. Svar: x(1) 2. Løsningsforslag: One step with Euler s method gives x 1 = x 0 + x 0 = 2. b. Estimate x(1) by using one step with the quadratic Taylor method. Svar: x(1) 2.5. Løsningsforslag: One step with quadratic Taylor gives x 1 = x 0 + x x 0 =
231 c. Estimate x(1) by using one step with Euler s midpoint method. Svar: x(1) 2.5. Løsningsforslag: One step with Euler s midpoint method gives x 1/2 = x x 0 = 3 2 x 1 = x 0 + x 1/2 = 5 2 = 2.5. d. Estimate x(1) by using one step with the Runge Kutta fourth order method. Svar: x(1) Løsningsforslag: With Runge-Kuttas method we get k 0 = 1 k 1 = 1 + k 0 2 = 1.5 k 2 = 1 + k 1 2 = 1.75 k 3 = = 2.75 x 1 = x (k 0 + 2k 1 + 2k 2 + k 3 ) = ( ) e. Estimate x(1) by using two steps with the Runge Kutta fourth order method. Svar: x(1)
232 Løsningsforslag: With two steps in Runge-Kuttas method we get k 0 = 1 k 1 = 1 + k 0 4 = 1.25 k 2 = 1 + k 1 4 = k 3 = = x 1 = x (k 0 + 2k 1 + 2k 2 + k 3 ) k 0 = x 1 = k 1 = x 1 + k 0 4 k 2 = x 1 + k 1 4 k 3 = x 1 + k 2 2 x 2 = x (k 0 + 2k 1 + 2k 2 + k 3 ) f. Optional: Write a computer program that implements one of the above mentioned methods and use it to estimate the value of y(1) with 10, 100, 1000 and steps? Løsningsforslag: The code looks as follows if we use the fourth order Runge Kutta method: for N in [10,100,1000,10000]: xk=1 h=1.0/n for k in range(n): k0=xk k1=xk+h*k0/2 k2=xk+h*k1/2 k3=xk+h*k2 xk=xk+h*(k0+2.0*k1+2.0*k2+k3)/6 print xk If we run the code we get If we change N to 100,1000,10000 we get , , and g. Do the estimates seem to converge? Løsningsforslag: It looks like the values converge to e. 232
233 h. Solve the equation analytically and explain your numerical results. Løsningsforslag: The equation is of first order with linear coefficients, and we see that the solution is x(t) = e t, so that x(1) = e In this problem we are going to solve the equation x = f (t, x) = x sin t + sin t, x(0) = 2 + e, numerically on the interval [0,2π]. Løsningsforslag: The code can look as follows: from math import * xk=2.0+exp(1) tk=0.0 N=10 h=2.0*pi/n for k in range(n): xk=xk+h*(-xk*sin(tk)+sin(tk)) tk=tk+h print xk xk=2.0+exp(1) tk=0.0 for k in range(n): xkhalf=xk+h*(-xk*sin(tk)+sin(tk))/2.0 xk=xk+h*(-xkhalf*sin(tk+h/2.0)+sin(tk+h/2.0)) print xk a. Use Euler s method with 1, 2, 5, and 10 steps and plot the results. How does the solution evolve with the number of steps? Svar: Approximation at t = 2π: Euler s method with 1 step: x(2π) Euler s method with 2 steps: x(2π) Euler s method with 5 steps: x(2π) Euler s method with 10 steps: x(2π) Løsningsforslag: Euler s metode here takes the form x k+1 = x k +h( x k sin t k + sin t k ). b. Use Euler s midpoint method with 1 and 5 steps and plot the results. Svar: Approximation at t = 2π: 233
234 Euler s midpoint method with 1 step: x(2π) Euler s midpoint method with 5 steps: x(2π) Løsningsforslag: Euler s midpoint method here takes the form x k+1/2 = x k + h 2 ( x k sin t k + sin t k ) x 1 = x k + h( x k+1/2 sin(t k + h/2) + sin(t k + h/2)) c. Compare the results from Euler s midpoint method with those form Euler s method including the number of evaluations of f in each case. Which method seems to be best? Løsningsforslag: This differential equation is separable, and one can show that the solution is on the form 1 + De cos(t). In particular, the solution is periodic with period 2π, so that the solution should satisfy x(2π) = 2+e. If we run the code for different N you will see that it is first for N larger than 1000 that we begin to get close, so that we can not say anything for N as small as those given in the exercise When investigating the stability of a numerical method it is common to apply the method to the model equation x = λx, x(0) = 1 and check for which values of the step length h the solution blows up. a. Apply Euler s method to the model equation and determine the range of h-values that for which the solution remains bounded. b. Repeat (a) for Euler s midpoint method. c. Repeat (a) for the second order Taylor method. d. Repeat (a) for the fourth order Runge-Kutte method Rn-222 is a common radioactive isotope. It decays to 218-Po through α- decay with a half-life of 3.82 days. The average concentration is about 150 atoms per ml of air. Radon emanates naturally from the ground, and so is typically more abundant in cellars than in a sixth floor apartment. Certain rocks like granite emanates much more radon than other substances. In this exercise we assume that we have collected air samples from different places, and these samples have been placed in special containers so that no new Rn-222 (or any other element) may enter the sample after the sampling has been completed. We now want to measure the Rn-222 abundance as a function of time, f (t). 234
235 a. The abundance x(t) of Rn-222 is governed the differential equation x = λx. Solve the differential equation analytically and determine λ from the half-life given above. b. Make a plot of the solution for the first 10 days for the initial conditions x(0) = 100, 150, 200 and 300 atoms per ml. c. The different initial conditions give rise to a family of functions. Do any of the functions cross each other? Can you find a reason why they do/do not? d. The four initial conditions correspond to four different air samples. Two of them were taken from two different cellars, one was taken from an upstairs bedroom, and the fourth is an average control sample. Which is which? 398. In this problem we are going to use Euler s method to solve the differential equation you found in exercise 397 with the inital condition x(0) = 300 atoms per ml sample over a time period from 0 to 6 days. a. Use 3 time steps and make a plot where the points (t i, x i ) for each time step are marked. What is the relative error at each point? (Compare with the exact solution.) b. For each point computed by Euler s method, there is an exact solution curve that passes through the point. Determine these solutions and draw them in the plot you made in (a). c. Use Euler s midpoint method with 3 time steps to find the concentration of Rn-222 in the 300 atoms per ml sample after 6 days. Compare with the exact result, and your result from exercise 398. What are the relative errors at the computed points? d. Repeat (a), but use the quadratic Taylor method instead (Continuation exam 2009) The solution x(t) of the differential equation x +sin(t x ) x 2 = e t is equal to the solution x 1 (t) of the system of two equations x 1 = x 1, x 2 = et sin(t x 2 ) + x 2 1 x 1 = x 2, x 2 = et sin(t x 1 ) + x 2 2 x 1 = x 2, x 2 = et sin(t x 2 ) + x 2 1 x 1 = x 2, x 2 = et sin(t x 1 ) + x 2 1 Svar: The third alternative is correct. 235
236 Løsningsforslag: We define x 1 = x, x 2 = x 1. The equation can then be written as x 2 + sin(t x 2) x1 2 = et, so that x 2 = et sin(t x 2 ) + x1 2. The third alternative is therefore correct Solve the system x = 2y sin ( 4t 2 x ), x(0) = 1, x (0) = 2, y = 2x 1 2t 2 (x ) 2 + 3, y(0) = 1, y (0) = 0, numerically on the interval [0, 2]. Try both Euler s method and Euler s midpoint method with two time steps and plot the results. Svar: Euler with 2 steps: x(2) 7, x (2) , y(2) , y (2) Euler s midpoint method with 2 steps: x(2) , x (2) , y(2) , y (2) Løsningsforslag: In order to solve this exercise, it is most convenient to implement a function which returns the values for f (t, x). The two equations can be written as a first order system as x 1 = x 2 x 2 = 2y 1 sin ( 4t 2 x 1 ) y 1 = y 2 y 2 = 2x 1 1 2t 2 (x 2 ) 2 + 3, with the initial condition (x 1 (0), x 2 (0), y 1 (0), y 2 (0)) = x 0 = (1,2,1,0). We get that f (0, x 0 ) = (2,2 sin0,0, 2 1/(0 + 3)) = (2,2,0, 7/3), so that the first step with Euler s method with h = 1 gives We now get that x 1 = x 0 + f (0, x 0 ) = (1,2,1,0) + (2,2,0, 7/3) = (3,4,1, 7/3). f (1, x 1 ) = (4,2 sin(12), 7/3, 6 1/(32 + 3)) (4,2.5366, 7/3, ) so that the second step with Euler s method gives x 2 = x 1 + f (1, x 1 ) (3,4,1, 7/3) + (4,2.5366, 7/3, ) (7, , , ). 236
237 This means that our approximations become x(2) 7, x (2) , y(2) , y (2) For Euler s midpoint method the first step becomes x 1/2 = x 0 + f (0, x 0 )/2 = (1,2,1,0) + (2,2,0, 7/3)/2 = (2,3,1, 7/6) f (1/2, x 1/2 ) = (3,2 sin2, 7/6, 4 1/(9/2 + 3)) (3,1.0907, , ) x 1 = x 0 + f (1/2, x 1/2 ) (1,2,1,0) + (3,1.0907, , ) = (4, , , ). The second step becomes f (1, x 1 ) (3.0907, , , ) x 3/2 = x 1 + f (1, x 1 )/2 (4, , , ) + (3.0907, , , )/2 = (5.5454, , , ) f (3/2, x 3/2 ) (3.0680, , , ) x 2 = x 1 + f (3/2, x 3/2 ) (7.0680, , , ). This means that our approximations become x(2) , x (2) , y(2) , y (2) This exercise is based on example?? in which we modelled the movement of a ball thrown through air with the equations v 1 = c m v 2 1, v 1(0) = v 0x, v 2 = c m v 2 2 g, v 2(0) = v 0y, We now consider the launch of a rocket. In this case, the constants g and c will become complicated functions of the height y, and possibly also of x. We make the (rather unrealistic) assumption that c m = c 0 ay where c 0 is the air resistance constant at the surface of the earth and y is the height above the earth given in kilometers. We will also use the fact that gravity varies with the height according to the formula g = g 0 (y + r ) 2, where g 0 is the gravitational constant times the mass of the earth, and r is the radius of the earth. Finally, we use the facts that x = v 1 and y = v
238 a. Find the second order differential equation for the vertical motion (make sure that the positive direction is upwards). b. Rewrite the differential equation for the horizontal motion as a second order differential equation that deps on x, x, y and y. c. Rewrite the coupled second order equations from (a) and (b) as a system of four first order differential equations. d. Optional: Use a numerical method to find a solution at t = 1 hour for the initial conditions x(0) = y(0) = 0, x (0) = 200 km/h and y (0) = 4 Nh2 300 km/h. Use a = km 3 kg, g 0 = (km)2 m and c s 2 0 = 0.19 Nh2 km 2 kg. These units are not so important, but mean that distances can be measured in km and speeds in km/h Radon-222 is actually an intermediate decay product of a decay chain from Uranium-238. In this chain there are 16 subsequent decays which takes 238- U into a stable lead isotope (206-Pb). In one part of this chain 214-Pb decays through β-decay to 214-Bi which then decays through another β-decay to 214- Po. The two decays have the respective halflifes of 26.8 minutes and 19.7 minutes. Suppose that we start with a certain amount of 214-Pb atoms and 214-Bi atoms, we want to determine the amounts of 214-Pb and 214-Bi as functions of time. a. Phrase the problem as a system of two coupled differential equations. b. Solve the equations from (a) analytically. c. Suppose that the inital amounts of lead and bismuth are 600 atoms and 10 atoms respectively. Find the solutions for these initial conditions and plot the two functions for the first 1.5 hours. d. When is the amount of bismuth at its maximum? e. Compute the number of lead and bismuth atoms after 1 hour with Euler s method. Choose the number of steps to use yourself. f. Repeat (e), but use the fourth order Runge-Kutta method instead and the same number of steps as in (e). 238
239 403. A block of mass m is attached to a horizontal spring. As long as the displacement x (measured in centimeters) from the equilibrium position of the spring is small, we can model the force as a constant times this displacement, i.e. F = kx, where k = N/cm is the spring constant. (This is Hooke s law). We assume the motion of the spring to be along the x-axis and the position of the centre of mass of the block at time t to be x(t). We then know that the acceleration is given by a(t) = x (t). Newton s second law applied to the spring now yields mx (t) = kx(t). (10) Suppose that the block has mass m = 0.25kg and that the spring starts from rest in a position 5.0cm from its equilibrium so x(0) = 5.0 cm and x (0) = 0.0cm/s. a. Rewrite this second order differential equation (10) as a system of two coupled differential equations and solve the system analytically. b. Use the second order Runge-Kutta method to solve the set of differential equations in the domain t [0,1.5] seconds with 3 time steps, and plot the analytical and approximate numerical solutions together. c. Did your numerical method and the number of steps suffice to give a good approximation? 404. This is a continuation of exercise 403, and all the constants given in that problem will be reused here. We now consider the case of a vertical spring and denote the position of the block at time t by y(t). This means that in addition to the spring force, gravity will also influence the problem. If we take the positive y-direction to be up, the force of gravity will be given by F g = mg. (11) Applying Newton s second law we now obtain the differential equation my (t) = k y(t) mg. (12) The equilibrium position of the spring will now be slightly altered, but we assume that y = 0 corresponds to the horizontal spring equilibrium position. a. What is the new equilibrium position y 0? b. We let the spring start from rest 5.0cm above the new equilibrium, which means that we have x(0) = 5.0cm + y 0, x (0) = 0.0cm/s. Rewrite the second order differential equation as a system of two first order ones and solve the new set of equations analytically. 239
240 c. Choose a numerical method for solving the equations in the interval t [0,1.5] seconds. Choose a method and the number of time steps that you think should make the results good enough. d. Plot your new analytical and numerical solutions and compare with the graph from exercise 403. What are the differences? Did your choice of numerical method work better than the second order Runge-Kutta method in exercise 403? 405. a. (Continuation exam 2009) A program generates digital video where every frame contains points and there is 25 frames per second. For every second of video this gives bytes bytes bytes bytes b. Which of the following statements is true? The three base colors used in color images on computers are usually red, yellow and blue. An image of pixels is said to be 2 Megapixels large. Electromagnetic radiation with wavelength 0.5 mm is in the range of visible light. The three base colours used in color images on computers are usually red, green and blue Mark each of the following statements as true or false. a. A computational molecule must always be symmetric around the center point. b. Sharp edges in images correspond to large values of the second derivative along a line, i.e. large values of p i+1,j 2p i,j + p i+1,j, which corresponds to the numerical expression for the second derivative found in Chapter
241 407. Mark each of the following statements as true or false. a. Vector graphics scales better than raster graphics when you zoom in closely on it Dersom du i MATLAB taster inn kommandoene >> t=linspace(0,pi,100); >> x=exp(t).*sin(t); >> y=exp(-t).*sin(t); >> plot(x,y) >> axis( equal ) får du figuren nedenfor. Finn arealet til området avgrenset av kurven a. Bruk MATLAB-vektoren >> A=[ ; ; ] A = >> rref(a) ans =
242 til å finne alle løsninger av ligningssystemet b. Skriv vektoren i A x + 2y + 3z + u = 5 2x + y + 4z + 2u = 4 3x + y z + u = 1 som en lineærkombinasjon av tre av søylene 1 2 3, 2 1 1, 3 4 1, 410. a. Finn alle løsningene til ligningssystemet 4x + 2y + 2z = 0 3x 6y + 3z = 0 x + 4y 5z = 0 b. Vis at 1 er en egenverdi for matrisen A = og finn en tilhøre egenvektor c. Nedenfor ser du resultatet av en MATLAB-kjøring. Bruk denne til å finne de andre egenverdiene og egenvektorene til A. Velg egenvektorer med 120 heltallige koeffisienter, og skriv v = 0 som en lineærkombinasjon 0 av egenvektorer. >> A=[ ; ; ]; >> [u,v]=eig(a) u =
243 v = d. Et firma som driver med dagsutleie av tilhengere, har kontor i tre byer X, Y og Z. En tilhenger kan leveres tilbake ved et fritt valgt kontor uavhengig av hvor den ble leid. Til planlegging bruker firmaet en modell som sier at av de tilhengerne som en uke starter i X, vil 60% starte neste uke i X, 30% vil starte neste uke i Y og 10% vil starte neste uke i Z. Av de tilhengerne som startet i Y, vil 20% starte neste uke i X, 40% i Y og 40% i Z. Av de tilhengerne som startet i Z, vil 20% starte neste uke i X, 30% i Y og 50% i Z. Firmaet har totalt 120 tilhengere som alle i utgangspunktet er i by X. Hvordan fordeler tilhengerne seg på byene X, Y og Z etter n uker dersom modellen er korrekt? Hva skjer med fordelingen når n? 411. What code blocks are executed, and which are not? int smallnumber = 13; if ((smallnumber > 5) && (smallnumber < 10)){ System.out.println("Between 5 and 10"); } if ((smallnumber > 10) && (smallnumber < 15)){ System.out.println("Between 10 and 15"); } if ((smallnumber > 15) && (smallnumber <20)){ System.out.println("Between 15 and 20"); } What would happen if the first line was changed to int smallnumber = 10; // the rest unchanged 243
244 Løsningsforslag: Since 13 is both larger than 10 and smaller than 15, the middle block is executed. For the other two blocks, only one of the parts is true, so the code isn t executed. If we use 10 instead, nothing is executed. This is because 10 < 10 is false This code block boolean[] truthvalues = {false, true}; for (boolean x : truthvalues){ for (boolean y : truthvalues){ System.out.printf("%b and %b is %b\n", x, y, x && y); } } produces a truth table for. Modify it to make truth tables for eaxh statement. Løsningsforslag: In each case, we write the whole code. Note that the first two parts simply have very minor changes, whereas the third part needs an additional nested layer. a. Løsningsforslag: can be used directly. boolean[] truthvalues = {false, true}; for (boolean x : truthvalues){ for (boolean y : truthvalues){ System.out.printf("%b or %b is %b\n", x, y, x y); } } b. Løsningsforslag: Truth table for implication,, using x y = x y: boolean[] truthvalues = {false, true}; for (boolean x : truthvalues){ for (boolean y : truthvalues){ System.out.printf("%b implies %b is %b\n", x, y,!x y); } } c. z (x y) Løsningsforslag: We use that z (x y) = z x y 244
245 boolean[] truthvalues = {false, true}; for (boolean x : truthvalues){ for (boolean y : truthvalues){ for (boolean z : truthvalues){ System.out.printf("%b implies %b or %b is %b\n", z, x, y,!z x y); } } } 413. Convert to decimal. Convert 3.75 to binary. Løsningsforslag: = = Here I cheated and used the calculator. To go the other way, 3.75 = = Compute the values of the smallest and the largest double as a decimal number. Løsningsforslag: Using the calculator, we find that the largest is ( ) = Math ERROR Oops! The number is too large for my calculator. What now? Trying Java with the same formula, as in double maxdouble = (2-Math.pow(2, -52)) * Math.pow(2,1023); System.out.println(maxDouble); returns E308 So the maximal double is Note that expanding the parantheses would lead to an error: double maxdouble = 2 * Math.pow(2,1023) - Math.pow(2, -52) * Math.pow(2,1023); System.out.println(maxDouble); 245
246 yields Infinity since = is too large for a double. Similarly, we find the smallest double as double mindouble = Math.pow(2, -1074); System.out.println(minDouble); returns 4.9E-324 so the minimal double is See how Java handles 0/0, 1/0 and 1/0 for integers (use int). Also check how Java handles 1 (use Math.sqrt). Løsningsforslag: Each of the expressions 0/0, 1/0 and 1/0 for integers lead to compilation errors. Running double rootofnegative = Math.sqrt(-1); System.out.println(rootOfNegative); returns NaN Convert the float f to long. Løsningsforslag: long converted = (long) f; 417. The associative law for multiplication states that (ab)c = a(bc). Run this code: float a=0.25e-12f; float b=4e12f; float c=5e35f; System.out.println((a*b)*c); System.out.println(a*(b*c)); What happens? Change all the floats into doubles, and try again. What has changed? Can you create a similar problem with doubles? Løsningsforslag: The output from running the code is 5.0E35 Infinity 246
247 Changing to doubles, we get from both computations. The problem is that bc is too large for a float, so that infinity is returned when this computation comes first. To get the same problem for double, we need to input larger numbers. Trial and error, and remembering the result from Exercise 414, we get the same type of result from running double a=0.25e-12; double b=4e12; double c=5e305; System.out.println((a*b)*c); System.out.println(a*(b*c)); 418. In this exercise, we will use Java to solve quadratic equations. The formula for solving the quadratic equation is x 0 = b+ b 2 4ac 2a ax 2 + bx + c = 0 x 1 = b b 2 4ac 2a. Choose values for a,b,c as floats, and write a programme that computes these two solutions. Note that the square root is found in Java as Math.sqrt. Then add a test to the programme, checking whether the numbers you have calculated actually solves the original problem. Try out your programme on these four sets of coefficients. a b c What happens? Why? If you get a possible loss of precisionerror, explicitly cast to float. Løsningsforslag: Here is code for the programme, initalized with the first set of coefficients from the table. It would be better to print a more informative statement. float a =1.0f; float b = 2.0f; float c = -3.0f; float x_0 = (float) (-b + Math.sqrt(b*b - 4*a*c))/(2*a); float x_1 = (float) (-b - Math.sqrt(b*b - 4*a*c))/(2*a); 247
248 System.out.println(x_0); System.out.println(x_1); //test. This should return 0 System.out.println(a*x_0*x_0 + b*x_0+c); System.out.println(a*x_1*x_1 + b*x_1+c); This returns In the next set of values for a,b,c, we get The third: NaN NaN NaN NaN Looking at the computation, we see that we try to compute the square root of a negative number, and this returns NaN as in Exercise 415. The last: Here the two solutions give 1 instead of 0 when plugged into the original equation. The reason is that there are errors coming from rounding. If all the variables are changed into doubles (and we delete the casting to float), the output will be E E E-9 248
249 We see that the approximate solution is actually a bit too large, and 0 a bit to small. Also, the test doesn t return 0, but numbers quite close to 0, which is to be expected because of rounding errors One can use floats in loops, which is practical if we want for instance points on a graph. Try to use a for loop of the form for (double x = startvalue, x < stopvalue, x = x + increment){...} to compute points on the graph of f (x) = sin x in the interval [ 7, 7]. To make sure that the point are close enough to get a nice graph from plotting them, compute the sine for each of the points 7, 6.99 and so forth. Then try to do the same computation using an int as index in the loop. Løsningsforslag: Here is the code for writing the points to the terminal window: for (double x = -7.0; x<7.0; x+= 0.01){ double y = Math.sin(x); System.out.printf("Point (%f, %f)\n ", x, y); } To find the easiest formulation for the range of an integer variable, note that if we multiply with a hundred, the increment is changed to +1. So we can write for(int i = -700; i< 700; i++){ double x = ((double) i)/100; double y = Math.sin(x); System.out.printf("Point (%f, %f)\n ", x, y); } Note that we also need to compute x, and we need to make sure that i /100 is not considered integer division In this exercise, we will compute as many powers of two that we can, using the primitive numerical types in Java. Start by defining int power = 2, and multiply repeatedly by 2. Check (how?) if the computation is correct using int, and if it isn t, convert to long. When this also fails, convert to float. When this fails, convert to double. Finally, write a statement about the largest powers handled by the different types. Can you modify the programme to work with powers of 3? Løsningsforslag: There are many ways to solve this exercise, so if your solution doesn t resemble this one, don t worry. int power = 1; 249
250 int powerof2 = 2; int onelower = 1; while (powerof2 > onelower){ System.out.println(powerOf2); powerof2 *= 2; onelower *= 2; power ++; } System.out.printf("Longs from power %d\n", power); long powerof2l = 2*(long) onelower; long onelowerl = (long) onelower; while (powerof2l > onelowerl){ System.out.println(powerOf2L); powerof2l *= 2; onelowerl *= 2; power ++; } System.out.printf("Floats from power %d\n", power); float powerof2f = 2* (float) onelowerl; float onelowerf = (float) onelowerl; Float infinity = new Float(Float.POSITIVE_INFINITY); while (powerof2f < infinity){ System.out.println(powerOf2f); powerof2f *= 2; onelowerf *= 2; power ++; } System.out.printf("Floats from power %d\n", power); double powerof2double = 2* (double) onelowerf; double infinitydouble = (double) infinity; while (powerof2double < infinitydouble){ System.out.println(powerOf2Double); powerof2double *= 2; power ++; } System.out.printf("Final power is %d\n", power); Changing all instances of 2 into 3s actually works, as a test it stops at Create multiplication and addition tables for ±, NaN, 0 and +0. To get the values, use for instance the wrapper class Float, as in 250
251 Float minusinfinity = new Float(Float.NEGATIVE_INFINITY); Løsningsforslag: This code produces the tables. It is not the simplest construction for the problem, and it might be better to format the output differently. Float minusinfinity = new Float(Float.NEGATIVE_INFINITY); Float plusinfinity = new Float(Float.POSITIVE_INFINITY); Float nan = new Float(Float.NaN); Float zero = new Float(0.0f); Float minuszero = new Float(-0.0f); Float[] specialfloats = new Float[5]; specialfloats[0] = minusinfinity; specialfloats[1] = plusinfinity; specialfloats[2] = nan; specialfloats[3] = zero; specialfloats[4] = minuszero; //multiplication table: for (Float special : specialfloats){ for (Float special2 : specialfloats){ System.out.printf("%f * %f = %f\n", special, special2, special * special2); } } //addition table: for (Float special : specialfloats){ for (Float special2 : specialfloats){ System.out.printf("%f + %f = %f\n", special, special2, special + special2); } } 422. Add another method to the Combinatorics class called computecatalan. This method takes one input and gives one output. The mathematical formula for the nth Catalan number is ( ) C n = 1 2n for n 0. n + 1 n 251
252 The input should be n, the output C n. To check your programming, produce the first few Catalan numbers, and compare with " from the online encyclopedia of integer sequences. Løsningsforslag: We can use the previously defined method computebinomialcoeff. It is a fact that the Catalan numbers are integers, so we will use the int type. public static int computecatalan(int n){ return computebinomialcoeff(2*n,n)/(n+1); } The first few values are 1, 1, 2, 5, 14, We will now implement the functions f : A B, where and the function f is defined by A = {0, 1, 2,,n 1} and B = {0, 1, 2,, m 1} f (a) = k a mod m. See Example??. If you want a more challenging exercise, look only at the Example, and produce a Java programme for these tasks. Otherwise, read the following hints. To initialize A, first give a value to n, define A as an array of this length, and define A[i ] = i in a loop. Do the same for B. Then declare the function f as an array of the same length as A, and define f [i ] as in the pseudocode in the example. The most involved part of this exercise is to compute the number numberofvalues correctly. Do this! Finally, write a statement if f is injective or surjective. If you want to check your programme, use it for some of the values in the main text. Løsningsforslag: Here is a possible programme. Note that the break statement prevents repetitions to be counted; each value is counted only once. public class FunctionFromRemainders{ public static void main(string[] args){ int n = 7; int m = 8; int k = 3; int[] seta = new int[n]; int[] setb = new int[m]; 252
253 } } int[] functionf = new int[n]; int numberofvalues = 0; for (int i = 0; i < n; i++){ seta[i] = i; } for (int i = 0; i < m; i++){ setb[i] = i; } for (int i = 0; i < n; i++){ functionf[i] = (i*k) % m; } for (int b : setb){ for (int i = 0; i < n; i++){ if (b == functionf[i]){ numberofvalues ++; break; } } } if (numberofvalues == n){ System.out.println("Injective!"); } if (numberofvalues == m){ System.out.println("Surjective!"); } 424. Write down the precise steps for multiplication of a single digit with an arbitrary integer, similar to the description of addition. Løsningsforslag: Multiply the single digit number with the ones digit. Thinking of the answer as tens plus ones, record the ones in the ones-place of the answer, and carry the tens. For each step after this one, move one place to the left in the multiple digit number and in the answer. At each step, multiply the digit with the current digit in the multiple digit number, and add whatevers been carried. Record the ones in the current digit of the answer, and carry the tens. Repeat until the of the multiple digit number, possibly takning into account a final carried digit. 253
254 425. What is ? Løsningsforslag: = = = Write down the addition and multiplication tables for arithmetic in base 3, using the digits 0,1 and 2. Løsningsforslag: and 427. Add and Løsningsforslag: Multiply and Løsningsforslag: Write 3027 in binary. Løsningsforslag: 3027 = = = = = = = = = = = = (13) 254
255 Thus 3027 = Check how Java deals with division involving one negative and one positive number. Løsningsforslag: We run the two possibilities we have (using ±7/3), first with negative numerator: System.out.printf("-7/3 = %d\n", (-7)/3);//quotient System.out.printf("-7 %% 3 = %d\n",(- 7) % 3); //remainder returns -7/3 = -2-7 % 3 = -1 Then with negative denominator: System.out.printf("7/-3 = %d\n", 7/(-3));//quotient System.out.printf("7 %% -3 = %d\n", 7 % (-3)); //remainder returns 7/-3 = -2 7 % -3 = 1 In both cases, the result of dividing yields the quotient rounded towards 0, and the remainder is given such that numer ator = quotient denominator + remainder 431. Determine, for each pair of integers, whether they are congruent modulo 6. Løsningsforslag: a. 13 and 45 Løsningsforslag: The remainders are 1 and 3, so these numbers are not congruent modulo 6. b. 2 and 28 Løsningsforslag: The remainders are 4 in both cases, so these are congruent modulo 6. Note that Java would produce different values with the %-operation. 255
256 c. 123 and 21 Løsningsforslag: The remainders are 3 in both cases, so they are congruent modulo 6. d. 123 and 21 Løsningsforslag: negative ones. Since the positive numbers are congruent, so are the 432. Check that the symbol ^ works as exclusive or, by displaying 43 ^ 3245 in binary. The number you ll get is Løsningsforslag: Running String binaryxor = String.format("%32s", Integer.toBinaryString(43 ^ 3245)).replace(, 0 ); System.out.println(binaryXor); yields We can check the answer; running String binary3206 = String.format("%32s", Integer.toBinaryString(3206)).replace(, 0 ); System.out.println(binary3206); yields the same result It is not allowed to use modulo 0, %0, in Java (because of division by zero). Check how Java treats modulo 1. Løsningsforslag: We can run, for instance for (int i = -5; i<5; i++){ System.out.println(i % 1); } Apparently, %1 always returns For each pair of numbers, convert them to binary, add them and multiply them in binary, and convert the answer back to decimal to check your answer. Løsningsforslag: a. 7 and 8 Løsningsforslag: 7 = and 8 = When computing nothing is carried, and we up with = = 15. When multiplying, again nothing is carried, and we up with = =
257 b. 45 and 5 Løsningsforslag: 45 = and 5 = Summing, we get = = 50. Multiplying yields The answer is = = 225. c. 256 and 13 Løsningsforslag: 256 = and 13 = Adding doesn t need any carrying, = = = 269. Multiplying is also easy, we up with Converting back to decimal gives = = = Hexadecimal numbers, numbers in base 16, are often used in computer science. In this exercise, we consider some aspects of these numbers. The digits are A B C D E F C, for instance, represents 12, and 2C represents = 44. Løsningsforslag: a. Find the decimal representation of the hexadecimal number 4AB2. Løsningsforslag: 4AB2 = = b. Add the two hexadecimal numbers 1A and B2E. If necessary, write down an addition table. Løsningsforslag: 1 The difficult part is that A + E = A + B 2 E B
258 c. Multiply the two numbers 1A and B2E. If necessary, write down a multiplication table. Løsningsforslag: 1 A B 2 E 6 F C C B 2 E A C d. Using the same procedure as in Equation??, find the hexadecimal representation of Løsningsforslag: = = = = The conclusion is that = 3B e. Transforming between hexadecimal numbers and binary numbers can be performed digit by digit in the hexadecimal number, because four binary digits correspond exactly to one hexadecimal digit. Write down the correspondence table, and use it to write 4E 24C in binary and in hexadecimal. Løsningsforslag: The table is as follows: binary hexadecimal A 1011 B 1100 C 1101 D 1110 E 1111 F 258
259 We then see that and 4E 24C = = 4E 6. Note that the first 0 in the binary representation of 4E24C could be omitted, and that an extra 0 has to be put in to get 4 = 0100 when going in the other direction Subtraction is typically performed by borrowing instead of carrying. We can think of this as carrying 1, as in the following computation of : If we try to do this for , we will up with a problem: ? 8 5 One of the good things about two s complement is that this problem doesn t occur, so subtraction of binary integers with a fixed number of bits always works. For instance, computing 2 5 with four bits ( keeping in mind that = 1 2 ): ? The answer contains a question mark, but since we only keep four bits, it is discarded, and we are left with the (correct) answer. Check in examples that a + ( b), computed using addition, is the same as a b computed using subtraction, for binary numbers with four bits. Can you prove that this is always true? Løsningsforslag: We start with an example, with a = 5 = and b = 2 = Then we also need b = 2 = Then
260 To prove that this always works is somewhat difficult. One way is to change focus, and regard all the numbers as being positive! Formally, we do this by adding 16 to the negative numbers. This means that for instance 1001, which in two s complement is 7, is considered as 9 = 7+16, which is the ordinary interpretation of the binary number Restricting to four bits means that we work modulo 16. Then if a > b (when both are considered as positive numbers), subtracting a b works as it usually does for positive numbers. Also, taking negatives is the same as subtracting from 16, so that b = 16 b (the computation can be performed with five bits, and the first bit can be discarded). Therefore, a + ( b) is equal to the ordinary sum of the two positive numbers a + (16 b), considered modulo 16, and this gives the same answer as the natural subtraction a b. If a < b we can prolong to five bits, exchange a by a + 16, do the same, and finally discard the first bit again. Modulo 16, this gives the same result Using the representation with four bits, perform these multiplications. For each multiplication, try to predict the answer before computing it. Løsningsforslag: In each case, predicting the answer really means to perform the operation for ordinary numbers, reduce modulo 16, and, if the remainder is greater than 7, subtract 16. The xs represent bits that we don t need to compute, as they are discarded. a. 2 3 Løsningsforslag: b. ( 2) ( 3) Løsningsforslag: x x x 0 0 x x x 0 x x x x x x 0 1 x x x 1 x x x
261 c. 2 4 Løsningsforslag: x x x 0 0 x x x 0 x x x d. 2 5 Løsningsforslag: x x x 0 0 x x x 0 x x x e. ( 3) 2 Løsningsforslag: x x x 1 0 x x x 0 x x x f. ( 6) 7 Løsningsforslag: x x x 0 0 x x x 1 x x x
262 438. Bitwise operations can be used to set flags. This means that the states of some system are described using several switches, that could be turned on or off. We will model this using bitwise operations using the integer type byte, which has 8 bits. To get the binary representation as a binary String, use byte abyte = 57; int theint = 0; if (abyte < 0){ theint = abyte; } else{ theint = abyte; } String binarybyte = String.format("%8s", Integer.toBinaryString(theInt)).replace(, 0 ); The +256 is a trick to alleviate the problems from casting to int. The bit in the 16-place is set (the switch is turned on) if its value is 1. Løsningsforslag: a. Explain why the bit in the 4-place is set by this code (statebyte represents the current value for the states). Print the binary strings for different statebytes so that you see both what happens if this bit was set and if it wasn t set before running the code. // statebyte is already defined statebyte = (byte) (statebyte 4); The bitwise operations are performed as int, so we need to cast to byte in the. Løsningsforslag: In other places than the four-bit, 4 has 0. Now 0 0 = 0 and 1 0 = 1, so in either case, nothing is changed. In the four-bit, 4 has 1. Since 1 1 = 1 and 0 1 = 1, in either case the four-bit is set. b. Explain why the bit in the 4-place is turned off by this code. Again, give examples both with the 4-bit set and not set before running this code block. // statebyte is already defined statebyte = (byte) (statebyte & -5); Løsningsforslag: 5 is the number that has a 0 in the four-bit, and 1 everywhere else. In places other than the four-bit, using 0 1 = 0 and 1 1 = 1, 262
263 we see that nothing is changed. In the four-bit, 0 0 = 0 and 1 0 = 0, so in either case the flag is turned off. c. What does exclusive or (^) with 0 do? What does exclusive or with 4 do? What does exclusive or with 1 do? Løsningsforslag: 0 has 0 in all bits. 1 0 = 1 and 0 0 = 0, so nothing happens. 4 has 0 in all places different from the four-bit, so nothing happens there. In the four-bit, 0 1 = 1 and 1 1 = 0, so the value in this place is switched from on to off or from off to on. 1 has 1 in all bits, so as in the previous step, we see that all bits are changed. Thus a ^ -1 = ~a. d. Given two integers intx and inty, what is the value of each of them after running this code: intx = intx ^ inty; inty = intx ^ inty; intx = intx ^ inty; If it is difficult to see what happens, run a couple of examples. Løsningsforslag: After the first step, intx is changed in all bits where inty has a 1. After the second step, inty gets the value computed from intx by changing all the bits were inty had a one again. Thus inty now has the original value of intx. Another way to think about intx after the first step, is to say that it comes from inty by changing all the bits were intx has a one. Since inty after step two is the original intx, after the third step, the changes in inty to intx in the first step are undone, and intx gets the original value of inty. To conclude: The two variables change their values! 439. Run the code for approximations of π with 1000, 2000 and iterations. How many digits do you believe are correct? Løsningsforslag: 1000 iterations give iterations give iterations give To compare with the actual value, we call Math.PI to get We see that even with ten thousand iterations, this method isn t very good. 263
264 440. Find the sum of the integers underlying the chars in the English alphabet. Løsningsforslag: We need to cast each of the characters a, b,..., z to int and sum the results. This code performs these operations, keeping a running total. int sumofchars = 0; for (char c = a ; c <= z ; c++){ sumofchars += (int) c; } The answer is Note that if we drop the explicit cast (int), Java casts implicitly for us Find the smallest n such that n i 2 i=1 is too large to be represented as an int. Løsningsforslag: An easy solution is to compute using longs, and compare with the largest int, also represented as a long-. Here is code using this approach. long maxint = Integer.MAX_VALUE; long runningtotal = 0; int i = 0; //summation index while (runningtotal < maxint){ i ++; runningtotal += i*i; } System.out.println(i); The answer turns out to be In the television show Futurama, two robots having serial numbers and are delighted to find that both of them have serial numbers that are expressible as a sum of two cubes. Another example is 35 = 8+27 = Find the expressions as sums of two cubes for the two serial numbers. Hint: Cubes can also be negative. Løsningsforslag: There are many ways to solve this exercise. We will take an approach that hopefully keeps the programming understandable. Since the negative cubes are the negatives of the positive cubes, we can make an array of positive cubes, and combine cubes with plus or minus. To make sure that we have enough cubes, we could make the array long enough to hold all cubes less 264
265 than the number we re interested in. This would work if we knew the cubes were positive! Since the cubes can be negative as well, we increase the length of the array by including the cubes of all numbers whose square is smaller than the number we re interested in. This is a crude solution, and the following code performs a lot of unnecessary work. A closer analysis of the problem would yield significantly reduced running time. //int n = ; int n = ; int numberofcubes = (int) Math.sqrt(n); // numberofcubes is more than large enough int[] cubes = new int[numberofcubes]; for (int i = 1; i <= numberofcubes; i++){ cubes[i-1] = i*i*i; } for (int i : cubes){ for (int j : cubes){ if (i + j == n){ System.out.printf("%d + %d = %d\n", i,j,n); } if (i-j == n){ System.out.printf("%d - %d = %d\n", i,j,n); } } } In the, this gives us that = = = = ( 951) The value of the natural logarithm at 2, ln2, can be computed by the infinite sum ( 1) n+1 ln2 = n n=1 This is a standard result in connection with Taylor series. By experimenting with the number of terms, try to find a numerical approximation for ln2. Compare this with the result of calling Math.log(2). Løsningsforslag: The code is relatively straight-forward. Note that ( 1) n+1 is 1 if n is odd, 1 if it is even, so we check for parity using the test i % 2 ==0. 265
266 int n = 100; double runningsum = 0.0; for (int i = 1; i < n; i++){ if (i % 2 == 0){ runningsum -= 1.0/i; } else{ runningsum += 1.0/i; } } System.out.println(runningSum); Calling Math.log(2) gives You will need a large number n to get close to this number In the theory of Fourier series, a standard exercise shows that 1 n 2 = π2 6 n=1 By experimenting with the number of terms, try to find a numerical approximation for π 2. Compare this with the result of calling Math.PI*Math.PI. Also compare the number of terms needed to get good approximations with the number of terms needed in Exercise 443. Løsningsforslag: We sum the series, up to a chosen number of terms n, and multiply by 6, to get the approximation for π 2. This code does this for us: int n = 100; double runningsum = 0.0; for (int i = 1; i < n; i++){ runningsum += 1.0/(i*i); } runningsum *= 6; System.out.println(runningSum); Calling Math.PI*Math.PI yields Again, we need many terms to get a good approximation Write down and compute these sums. 4 i=0 2i 2 3n=1 n 3 10 n=1 n 266
267 Løsningsforslag: 4 i=0 2i 2 = = 10 3n=1 n 3 = = n=1 n = = Sum the finite arithmetic series Løsningsforslag: Here s = 8, t = 3, and the last term is 71 = , so n = 21. Therefore the sum is 447. Sum the finite geometric series (n + 1)(2s + nt) 22 ( ) = = Løsningsforslag: Here r = 2 and k = 3. The last term is = 2 3 8, so n = 8. Therefore, the sum is r rk n+1 1 k = Sum the infinite geometric sequence = Løsningsforslag: Here r = 17 and k = 1/7, which is less than 1, so the series is convergent. The sum is therefore r 1 k = = We will again consider the harmonic series
268 We will prove that the series diverges to by thinking in binary, and performing some approximations. More precisely, we will round each term 1 n down to the nearest 1 2 smaller than it, and sum those terms instead. At each step, since we re m always rounding down, we will get a lower bound for the sum. Finally, we will see divergence because the lower bound diverges to. Løsningsforslag: a. Write explicitly the series up to the term 1 16, and round each term down 1 to the closest 2. What is the lower bound for m coming from this? 268
269 Løsningsforslag: If we sum the right hand sides, we get = = 3 b. Use the binary logarithm to find a formula for m such that 1 n rounds down to 1 2. m Løsningsforslag: 1/n rounds down to 1/2 m if 2 m 1 < n 2 m. In terms of the binary logarithm, this means that m 1 < log 2 (n) m
270 c. How many terms round down to the same 1 2 m? Løsningsforslag: The number of terms rounding down to 1/2 m can be found by counting the numbers in the set {2 m 1 + 1, 2 m 1 + 2,,2 m = 2 m m 1 }. We see that there are exactly 2 m 1 numbers in this set. d. Use the above to find explicitly a lower bound for the sum m. Løsningsforslag: From c), we see that the sum of the terms rounding down to 1/2 m is 2 m 1 1/2 m = 1/2. Therefore we get the 1 in the beginning, plus one half for each i = 1, 2, 3,,m, so the answer for the lower bound is 1 + m 2. e. Conclude from d) that the lower bound diverges to infinity, and therefore the original sum also diverges to infinity. Løsningsforslag: Since our sum is greater than a sum with partial sums 1+ m 2, and since this sequence goes to infinity, the sum we re interested in must also go to infinity Summing the finite geometric series is performed in Theorem??. Using that, for n > m, n n m a i = a i find a formula for i=m+1 n i=0 i=m+1 rk i a i i=0 Check your formula by applying Theorem?? directly, using rk m+1 instead of r. Løsningsforslag: The formula in the text of the exercise yields n i=m+1 rk i = n m rk i rk i i=0 Both terms on the right are given by the formula in Theorem??: The formula in the text of the exercise yields n i=m+1 rk i = i=0 i=0 i=0 n m rk i rk i = r rkn+1 1 k 270 r rkm+1 1 k
271 Since the denominators are the same, summing the fractions is straight-forward, and we get n i=m+1 rk i = r rkn+1 (r rk m+1 ) 1 k Another way to compute this is to realize that n i=m+1 rk i n m 1 = rk m+1 k i i=0 = rkm+1 rk n+1 1 k This is a geometric series with first term rk m+1 and quotient k. By appealing to Theorem?? again, we get n m 1 i=0 Again, we get the same result. rk m+1 k i = rkm+1 rk m+1 k n m 1 k = rkm+1 rk n+1 1 k 451. Theorem?? produces a formula for the infinite geometric series. Find a formula for rk i i=m when k < 1 in two ways. One is to subtract a convenient finite geometric series. The other is to consider this series as a full geometric series with first term rk m. Løsningsforslag: We can write rk i = rk i m 1 rk i i=m i=0 Using Theorem?? for the infinite series and Theorem?? fir the finite series yields Simplifying, we get i=m rk i = rk i m 1 i=m i=0 i=0 rk i = i=0 r 1 k r rkm 1 k rk i = r 1 k r rkm 1 k = r (r rkm ) = rkm 1 k 1 k We can compute the sum by appealing to Theorem??, by writing i=m We get the same result twice. rk i = rk m k i = rkm 1 k i=0 271
272 452. In this exercise, we define a couple of sets of integers, and let Java compute the set-theoretical operations. We first fix our universe, which will consist of the 11 elements uni ver se = {0,1,2,3,4,5,6,7,8,9,10} A and B willl be some more or less random subsets. The initialization of what we ve discussed so far can be done as follows: int[] universe = {0,1,2,3,4,5,6,7,8,9,10}; int[] seta = {0,1,2,3,4,5}; int[] setb = {2,3,5,7}; To check whether an element, say 3, is in the union of A and B, we can use the code block boolean isinunion = false; for (int numbera : seta) { if (3 == numbera) { isinunion = true; } } for (int numberb : setb) { if (3 == numberb) { isinunion = true; } } if (isinunion) { System.out.printf("%d is in the union\n", 3); } To check for all elements, we loop through the entire universe: for (int number : universe) { boolean isinuion = false; for (int numbera : seta) { if (number == numbera) { isinunion = true; } } for (int numberb : setb) { if (number == numberb) { isinunion = true; } 272
273 } } if (isinunion) { System.out.printf("%d is in the union\n", number); } Modify this programme to find the intersection. Also find the complement of A. For the more ambitious, modify the code so that fewer equalities are checked. Use for instance break. Løsningsforslag: We answer this exercise by giving the entire programme. Note that the structure for finding the boolean test variables is the same as in the text, it is only the way they are used that is different. //Initialization int[] universe = {0,1,2,3,4,5,6,7,8,9,10}; int[] seta = {0,1,2,3,4,5}; int[] setb = {2,3,5,7}; //Intersection: we need both in A and in B for (int number : universe){ boolean testa = false; boolean testb = false; for ( int numbera : seta){ if (number == numbera){ testa = true; } } } for ( int numberb : setb){ if (number == numberb){ testb = true; } } if (testa && testb){ System.out.printf("%d is in the union\n", number); } //Complement of A: for (int number : universe){ boolean testa = false; for ( int numbera : seta){ 273
274 } if (number == numbera){ testa = true; } } if (!testa){ System.out.printf("%d is in the complement of A\n", number); } 453. In this exercise, we will use Java to check whether a relation is a partial order. First, we define a set and a relation on it. This time, we use char. char[] seta = { a, b, c, d, e, f }; char[][] relation ={{ a, a },{ b, b },{ c, c },{ d, d }, { e, e },{ f, f },{ a, d },{ a, f },{ c, d }, { c, e },{ c, f },{ d, f }}; We need to check reflexivity, anti-symmetry and transitivity. To check for reflexivity, we create a pair (c,c) for each element c of A, and checks if it is in the relation. We then count how many times this happens, and if it happens as many times as there are elements in A, the relation is reflexive. int reflexivepairs = 0; for (char c : seta) { char[] cpair = new char[2]; cpair[0] = c; cpair[1] = c; for (char[] pair : relation) { if (pair[0] == cpair[0] && pair[1] == cpair[1]) { reflexivepairs++; } } } if(reflexivepairs == seta.length) { System.out.println("The relation is reflexive"); } Note that we checked the equality of pairs by checking both entries. To check for anti-symmetry, we search for pairs (x, y) and (y, x). If both are in the relation, we check whether x = y. Unless we find a counter-example, this condition holds. Therefore we intialize 274
275 boolean isantisymmetric = true; and change the value if we find a counter-example. boolean isantisymmetric = true; for (char[] pair : relation) { for (char[] newpair : relation) { if (newpair[0] == pair[1] && newpair[1] == pair[0] && pair[0]!= pair[1]) { isantisymmetric = false; } } } if (isantisymmetric) { System.out.println("The relation is antisymmetric"); } The main task left to you is to check for transitivity. As for antisymmetry, the condition holds unless we find a counter-example. We need to check, for all two pairs (x, y) and (y, z), whether (x, z) is also in the relation. Finally, write a statement if all three conditions are fulfilled. Løsningsforslag: We answer this exercise by giving the entire programme, with a note to what is added to the text of the exercise. //Initialization from the text char[] seta = { a, b, c, d, e, f }; char[][] relation ={{ a, a },{ b, b },{ c, c },{ d, d }, { e, e },{ f, f },{ a, d },{ a, f },{ c, d }, { c, e },{ c, f },{ d, f }}; //reflexivity from the text int reflexivepairs = 0; for (char c : seta){ char[] cpair = new char[2]; cpair[0] = c; cpair[1] = c; for (char[] pair : relation){ if (pair[0] == cpair[0] && pair[1]==cpair[1]){ reflexivepairs++; } } } 275
276 if(reflexivepairs == seta.length){ System.out.println("The relation is reflexive"); } //reflexivity s //antisymmetry from the text boolean isantisymmetric = true; for (char[] pair : relation){ for (char[] newpair : relation){ if (newpair[0] == pair[1] && newpair[1] == pair[0] && pair[0]!=pair[1]){ isantisymmetric = false; } } } if (isantisymmetric){ System.out.println("The relation is antisymmetric"); } //antisymmetry s //transitivity - new stuff boolean istransitive = true; for (char[] pair1 : relation ){ for (char[] pair2 : relation){ if (pair1[1]==pair2[0]){ //check if pair1[0],pair2[1] is in the relation char[] testpair = new char[2]; testpair[0] = pair1[0]; testpair[1] = pair2[1]; boolean test = false; for (char[] pair : relation){ if(testpair[0] == pair[0] && testpair[1]==pair[1]){ test = true; } } if (!test){ istransitive = false; } } } 276
277 } if (istransitive){ System.out.println("The relation is transitive"); } //transitivity s //if partial order: if(isantisymmetric && istransitive && reflexivepairs == seta.length){ System.out.println("All three conditions are fulfilled."); System.out.println("The relation is a partial order."); } 454. We will count the number of true and false statements in a Java generated truth table, as in Exercise 412. The expressions we will be considering have three variables x, y, z. In the beginning of this exercise, consider the expression x (y z). Løsningsforslag: By combining the code snippets in each part, you will get a complete programme for this problem. a. Declare an array of booleans, that is of type boolean[], to hold the values of the truth table. How long must the array be? How long would it have to be if there were 12 variables instead of just 3? Løsningsforslag: The length must be 2 3 = 8. If there were 12 variables, we would need 2 12 = This is because we have two choices for each variable. boolean[] truthtable = new boolean[8]; int index = 0; //keep track of index in truthtable b. Find a loop structure to generate the table as in Exercise 412. Inside the loop, fill the table with values instead of printing the values. Løsningsforslag: boolean[] truthvalues = {false, true}; for (boolean x : truthvalues){ for (boolean y : truthvalues){ for (boolean z : truthvalues){ truthtable[index] = x && (!y z); index++; } } 277
278 } c. Iterate through the table to find the number of times true appears. Write a statement about the number of true and false values. Løsningsforslag: int numberoftrue = 0; for (boolean tablevalue : truthtable){ if (tablevalue){ numberoftrue ++; } } System.out.println("Number of true"); System.out.println(numberOfTrue); System.out.println("Number of false"); System.out.println(8-numberOfTrue); d. Write an additional statement if the expression is a contradiction or a tautology. Løsningsforslag: if (numberoftrue == 0){ System.out.println("The expression is a contradiction"); } if (numberoftrue == 8){ System.out.println("The expression is a tautology"); } e. Modify the programme to test the expressions (x z) (y z) and (x z) (y z). Does it work as planned? Løsningsforslag: To check for (x z) (y z), we only need to change the innermost line in the loop to truthtable[index] =(x && z) && (y &&!z); Similarly, for (x z) (y z), we need truthtable[index] =(x z) (y!z); In the first case, we get a contradiction, in the second a tautology. 278
Exercises plotting. Øyvind Ryan
Exercises plotting Øyvind Ryan 19. februar 2013 1. Bruk Matlab til å tegne kurvene: % Oppgave 3.1.5 a) t=linspace(0,6*pi,100); plot(t.*cos(t),t.*sin(t)); % Oppgave 3.1.5 b) t=linspace(0,2*pi,100); plot(5*cos(t),3*sin(t));
Fasit til utvalgte oppgaver MAT1110, uka 15-19/2
Fasit til utvalgte oppgaver MAT1110, uka 15-19/2 Øyvind Ryan ([email protected]) February 19, 2010 Oppgave 3.6.1 Vi ser på ligningen Vi fullfører kvadratene: 4x 2 + 9y 2 + 32x 18y + 37 = 0. 4(x 2 + 8x
Oppgaver og fasit til seksjon
1 Oppgaver og fasit til seksjon 3.7-3.10 Oppgaver til seksjon 3.7 I oppgave 1 til 7 skal du avgjøre om feltet er konservativt og i så fall finne en potensialfunksjon. 1. F(x, ) = (x + x) i + x j. F(x,
Oppgaver og fasit til seksjon
1 Oppgaver og fasit til seksjon 3.1-3.3 Oppgaver til seksjon 3.1 1. Regn ut a b når a) a = ( 1, 3, 2) b = ( 2, 1, 7) b) a = (4, 3, 1) b = ( 6, 1, 0) 2. Finn arealet til parallellogrammet utspent av a =
Examples plotting. Øyvind Ryan
Examples plotting Øyvind Ryan 19. februar 2013 Example 0.1. Vi skal tegne grafen til f (x, y) = x 3 4y 2 over rektangelet x [ 3,3], y [ 5,5]. Vi lager først en oppdeling av de to intervallene vi er interessert
Examples MAT1110. Øyvind Ryan
Examples MAT1110 Øyvind Ryan 19. februar 2013 Example 0.1. Vi skal tegne grafen til f (x, y) = x 3 4y 2 over rektangelet x [ 3,3], y [ 5,5]. Vi lager først en oppdeling av de to intervallene vi er interessert
Fasit til utvalgte oppgaver MAT1110, uka 28/4-2/5
Fasit til utvalgte oppgaver MAT1110, uka 8/4-/5 Tom Lindstrøm ([email protected]) 5..5 a) Alle punktene i B har avstand til origo større enn 1, så d(0, B) må være minst 1. Ved å velge punkter på x-aksen
Oppgaver til seksjon med fasit
Oppgaver til seksjon.6-. med fasit Oppgaver til seksjon.6. Skriv b som en lineærkombinasjon av a og a når a = ( ( a = og b =.. Skriv b som en lineærkombinasjon av a, a og a når a = a =, a = og b = 5. (.
MAT1110: Obligatorisk oppgave 2, V Løsningsforslag
MAT1110: Obligatorisk oppgave 2, V-2015 Oppgave 1: a) Vi har Av 1 = ( 4 6 6 1 Løsningsforslag ) ( 3 2 ) = ( 24 16 ) = 8v 1, så v 1 er en egenvektor med egenverdi 8. Tilsvarende er ( ) ( ) ( ) 4 6 2 10
UNIVERSITETET I OSLO
UNIVERSITETET I OSLO Det matematisk-naturvitenskapelige fakultet Eksamen i: MAT Kalkulus og lineær algebra Eksamensdag: Onsdag 9 mai 9 Tid for eksamen: 4:3 8:3 Oppgavesettet er på 7 sider Vedlegg: Tillatte
Løsningsforslag til prøveeksamen i MAT 1110, våren 2006
Løsningsforslag til prøveeksamen i MAT, våren 6 Oppgave : a) Vi har C 5 3 II+( )I a + 3a 3a III+I 3 II 3 3 3 3 a + 3a 3a 3 a + 3a 3a III+II I+( ))II 3 3 3 a + 3a 3a 3 3 3 a + 3a 4 3 3a a + 3a 4 3 3a b)
MAT 1110: Obligatorisk oppgave 1, V-07: Løsningsforslag
1 MAT 111: Obligatorisk oppgave 1, V-7: Løsningsforslag Oppgave 1. a) Vi deriverer på vanlig måte: ( e (sinh x) x e x ) = = ex + e x = cosh x, ( e (cosh x) x + e x ) = = ex e x = sinh x Enkel algebra gir
Løsningsforslag til eksamen i MAT 1100 H07
Løsningsforslag til eksamen i MAT H7 DEL. (3 poeng Hva er den partiellderiverte f y når f(x, y, z = xeyz? xze yz e yz xe yz e yz + xze yz e yz + xze yz + xye yz Riktig svar: a xze yz Begrunnelse: Deriver
NTNU. MA1103 Flerdimensjonal Analyse våren Maple-øving 2. Viktig informasjon. Institutt for matematiske fag. maple02 28.
NTNU Institutt for matematiske fag MA1103 Flerdimensjonal Analyse våren 2011 Maple-øving 2 Fyll inn studieprogram: Fyll inn navn: 1. 2. 3. 4. Viktig informasjon Besvarelsen kan leveres som gruppearbeid
Løsningsforslag til eksamen i MAT 1100, H06
Løsningsforslag til eksamen i MAT, H6 DEL. poeng Hva er den partiellderiverte f z xyz cosxyz x sinyz + xyz cosyz xy cosyz x sinyz + xz cosyz cosyz xyz sinyz når fx, y, z = xz sinyz? Riktig svar b: x sinyz
Oppgaver og fasit til kapittel 6
1 Oppgaver og fasit til kapittel 6 Mange av oppgavene i dette kapitlet brukes for første gang, og det er sannsynligvis flere fasitfeil enn normalt. Finner du en feil, så send en melding til [email protected].
1. Finn egenverdiene og egenvektorene til matrisen A = 2 1 A =
Fasit MAT102 juni 2017 Oppgave 1 1. Finn egenverdiene og egenvektorene til matrisen ( ) 1 2 A = 2 1 Løsning: Egenverdiene er røttene til det karakteristiske polynom gitt ved determinanten av matrisen (
Løsningsforslag: MAT 1110 Obligatorisk oppgave 2, V-12
Løsningsforslag: MAT 0 Obligatorisk oppgave, V- Oppgave a Siden f har en annenderivert, må både funksjonen selv og dens deriverte være kontinuerlige, og det sikrer at vi i regningene nedenfor har 0 0 -uttrykk:
NTNU. MA1103 Flerdimensjonal analyse våren Maple/Matlab-øving 2. Viktig informasjon. Institutt for matematiske fag
NTNU Institutt for matematiske fag MA1103 Flerdimensjonal analyse våren 2012 Maple/Matlab-øving 2 Fyll inn studieprogram: Fyll inn navn: 1. 2. 3. 4. Viktig informasjon Besvarelsen kan leveres som gruppearbeid
Oppgaver og fasit til seksjon
1 Oppgaver og fasit til seksjon 3.4-3.6 Oppgaver til seksjon 3.4 1. Anta at f(x, y) = x 2 y 3 og r(t) = t 2 i + 3t j. Regn ut g (t) når g(t) = f(r(t)). 2. Anta at f(x, y) = x 2 e xy2 og r(t) = sin t i+cos
MAT1110. Obligatorisk oppgave 1 av 2
30. mai 2017 Innleveringsfrist MAT1110 Obligatorisk oppgave 1 av 2 Torsdag 23. FEBRUAR 2017, klokken 14:30 i obligkassen, som står i gangen utenfor ekspedisjonen i 7. etasje i Niels Henrik Abels hus. Instruksjoner
MAT Prøveeksamen 29. mai - Løsningsforslag
MAT0 - Prøveeksamen 9 mai - Løsningsforslag Oppgave Sett A = 4 4 0 x 0, x = x, b =, x 0 og la v, v, v betegne kolonnevektorene til A a) Skriv A x = y som en vektorlikning x Svar : Siden A x = [v v v ]
MAT1120 Plenumsregningen torsdag 26/8
MAT1120 Plenumsregningen torsdag 26/8 Øyvind Ryan ([email protected]) August 2010 Innføring i Matlab for dere som ikke har brukt det før Vi skal lære følgende ting i Matlab: Elementære operasjoner Denere
Computational comments. Øyvind Ryan
Computational comments Øyvind Ryan 19. februar 2013 MATLAB-kommentar: For å regne med vektorer i MATLAB, må du første skrive dem inn. Du kan skrive inn radvektorene a = (1, 2,3,0,5) og b = (3, 2.4, 2,0)
Noen MATLAB-koder. 1 Plotte en vanlig funksjon. Fredrik Meyer. 23. april 2013
Noen MATLAB-koder Fredrik Meyer 23. april 2013 1 Plotte en vanlig funksjon Anta at f : [a, b] R er en vanlig funksjon. La for eksempel f(x) = sin x+x for x i intervallet [2, 5]. Da kan vi bruke følgende
Løsningsforslag, eksamen MA1103 Flerdimensjonal analyse, 8.juni 2010
Norges teknisk naturvitenskapelige universitet Institutt for matematiske fag Side 1 av 7 Løsningsforslag, eksamen MA11 Flerdimensjonal analyse, 8.juni 21 Oppgave 1 a) Finn og klassifiser alle kritiske
Anbefalte oppgaver - Løsningsforslag
TMA415 Matematikk 2 Anbefalte oppgaver - Løsningsforslag Uke 7 15.1.3: Siden vektorfeltet er gitt ved F(x, y) = yi + xj må feltlinjene tilfredstille differensiallikningen eller y = x y, ( ) 1 2 y2 = x.
Løsningsforslag for flervariabel analyse med lineær algebra
FVLAboksol 5//8 5:47 page i # Løsningsforslag for flervariabel analyse med lineær algebra Øyvind Ryan Matematisk institutt Universitetet i Oslo 8. februar 5 FVLAboksol 5//8 5:47 page ii # ii FVLAboksol
Løsningsforslag AA6524 Matematikk 3MX Elever 7. juni eksamensoppgaver.org
Løsningsforslag AA654 Matematikk MX Elever 7. juni 004 eksamensoppgaver.org eksamensoppgaver.org Om løsningsforslaget Løsningsforslaget for matematikk eksamen i MX er gratis, og det er lastet ned på eksamensoppgaver.org.
Eksamen i MAT1100 H14: Løsningsforslag
Eksamen i MAT H4: Løsningsforslag Oppgave. ( poeng) Dersom f(x, y) x sin(xy ), er f y lik: A) sin(xy ) + xy cos(xy ) B) x cos(xy ) C) x y cos(xy ) D) sin(xy ) + x y cos(xy ) E) cos(xy ) Riktig svar: C):
Prøve i Matte 1000 BYFE DAFE 1000 Dato: 03. mars 2016 Hjelpemiddel: Kalkulator og formelark. Alle svar skal grunngis. Alle deloppgaver har lik vekt.
Prøve i Matte 1 BYFE DAFE 1 Dato: 3. mars 216 Hjelpemiddel: Kalkulator og formelark Alle svar skal grunngis. Alle deloppgaver har lik vekt. LØSNINGSFORSLAG Oppgave 1 Gitt matrisene A = [ 8 3 6 2 ] [ og
TMA4110 Matematikk 3 Eksamen høsten 2018 Løsning Side 1 av 9. Løsningsforslag. Vi setter opp totalmatrisen og gausseliminerer:
TMA4 Matematikk 3 Eksamen høsten 8 Løsning Side av 9 Løsningsforslag Oppgave Vi setter opp totalmatrisen og gausseliminerer: 8 5 4 8 3 36 8 4 8 8 8 Den siste matrisen her er på redusert trappeform, og
UNIVERSITETET I OSLO
UNIVERSITETET I OSLO Det matematisk-naturvitenskapelige fakultet Eksamen i MAT111 Prøveeksamen Eksamensdag: 5. juni 21. Tid for eksamen: 1. 13.3. Oppgavesettet er på 9 sider. Vedlegg: Tillatte hjelpemidler:
Prøveeksamen i MAT 1100, H-03 Løsningsforslag
Prøveeksamen i MAT, H- Løsningsforslag. Integralet cos x dx er lik: +sin x Riktig svar: c) arctan(sin x) + C. Begrunnelse: Sett u = sin x, da er du = cos x dx og vi får: cos x + sin x dx = du du = arctan
MA1102 Grunnkurs i analyse II Vår 2019
Norges teknisk naturvitenskapelige universitet Institutt for matematiske fag MA1102 Grunnkurs i analyse II Vår 2019 10.2.27 a) Vi skal vise at u + v 2 = u 2 + 2u v + v 2. (1) Som boka nevner på side 581,
Obligatorisk oppgave 1
Obligatorisk oppgave 1 a) Oppgaveteksten oppgir et vektorfelt f(x, y) F x, y = g x, y der f og g er oppgitt ved f x, y = x 3 3xy 1 og g x, y = y 3 + 3x y. Vi kan med dette regne ut Jacobimatrisen F x,
MA1201 Lineær algebra og geometri Løsningsforslag for eksamen gitt 3. desember 2007
Norges teknisknaturvitenskapelige universitet Institutt for matematiske fag MA101 Lineær algebra og geometri Løsningsforslag for eksamen gitt 3 desember 007 Oppgave 1 a) Vi ser på ligningssystemet x +
Løsningsforslag, midtsemesterprøve MA1103, 2.mars 2010
Norges teknisk naturvitenskapelige universitet Institutt for matematiske fag Side av 5 Løsningsforslag, midtsemesterprøve MA03,.mars 00 Oppgave Tegn figur og finn en parametrisering for skjæringskurven
Løsningsforslag til eksamen i MAT1110, 13/6-07
Løsningsforslag til eksamen i MAT, 3/6-7 Oppgaveteksten er gjengitt i kursiv Oppgave : a) Finn de stasjonære (kritiske) punktene til f(x, ) = x + 4x Løsning: Finner først de partiellderiverte: (x, ) x
UNIVERSITETET I OSLO
UNIVERSITETET I OSLO Det matematisk-naturvitenskapelige fakultet Deleksamen i: Eksamensdag: Fredag 1. april 2011 Tid for eksamen: 15.00 17.00 Oppgavesettet er på 7 sider. Vedlegg: Tillatte hjelpemidler:
Løsning, funksjoner av flere variable.
Ukeoppgaver, uke 3 Matematikk 3, funksjoner av flere variable 1 Løsning, funksjoner av flere variable Oppgave 1 a) = +=, b) =, =y3 d ) e ) = 3+= 3 Selv om ikke x er med kan det betraktes som funksjon av
Fasit MAT102 juni 2016
Fasit MAT02 juni 206. (a) Finn egenverdiene og egenvektorene til matrisen ( ) 6 A = 2 7 Svar: λ = 8 og ( ) x = y y ( ) /2, λ = 5 og ( ) x = y y ( ) for alle y 0. (b) Finn den generelle løsningen på systemet
Løsningsforslag. Oppgave 1 Gitt matrisene ] [ og C = A = 4 1 B = 2 1 3
Prøve i Matematikk BYFE DAFE Dato: 27. mai 26 Hjelpemiddel: Kalkulator og formelark Alle svar skal grunngis. Alle deloppgaver har lik vekt. Løsningsforslag Oppgave Gitt matrisene [ 2 A 4 B [ 2 og C [ 2
5.5 Komplekse egenverdier
5.5 Komplekse egenverdier Mange reelle n n matriser har komplekse egenverdier. Vi skal tolke slike matriser når n = 2. Ved å bytte ut R med C kan man snakke om komplekse vektorrom, komplekse matriser,
3x + 2y 8, 2x + 4y 8.
Oppgave En møbelfabrikk produserer bord og stoler Produksjonen av møbler skjer i to avdelinger, avdeling I og avdeling II Alle møbler må innom både avdeling I og avdeling II Det å produsere et bord tar
Alle svar skal grunngis. Alle deloppgaver har lik vekt.
Alle svar skal grunngis. Alle deloppgaver har lik vekt. Oppgave Vi denerer matrisene A, B, og C som A = [ ] 3, B = 5 9, C = 3 3. a) Regn ut følgende matrisesummer og matriseprodukter, om mulig. Dersom
dg = ( g P0 u)ds = ( ) = 0
NTNU Institutt for matematiske fag TMA4105 Matematikk 2, øving 8, vår 2011 Løsningsforslag Notasjon og merknader Som vanlig er enkelte oppgaver kopiert fra tidligere års løsningsforslag. Derfor kan notasjon,
Arne B. Sletsjøe. Oppgaver, MAT 1012
Arne B. Sletsjøe Oppgaver, MAT 101 1 En-variabel kalkulus 1.1 I de følgende oppgavene, i) finn alle kritiske punkter til f(x), ii) beskriv monotoniegenskapene til funksjonene ved å se på fortegnet til
R2 eksamen høsten 2017 løsningsforslag
R eksamen høsten 017 løsningsforslag DEL 1 Uten hjelpemidler Oppgave 1 (5 poeng) Deriver funksjonene a) f x sin3x f x cos3x 3 6cos3x sin x x sin x x sin x x x cos x sin x g x x x b) gx h x x cos x c) h
Vær OBS på at svarene på mange av oppgavene kan skrives på flere ulike måter!
Vær OBS på at svarene på mange av oppgavene kan skrives på flere ulike måter! Oppgave.. a x y = x + y = r r r +r r x y = y fri x y = y fri Vi får én fri variabel, og løsningens har følgelig dimensjon.
Løsningsforslag til eksamen i MA0002, Brukerkurs i matematikk B
Norges teknisk naturvitenskapelige universitet Institutt for matematiske fag Side 1 av 7 Løsningsforslag til eksamen i MA000, Brukerkurs i matematikk B 9. mai 01 Oppgave 1 a) Et plan i rommet har ligning
Løsningsforslag til eksamen i TMA4105 matematikk 2,
Norges teknisk naturvitenskapelige universitet Institutt for matematiske fag Side av Løsningsforslag til eksamen i TMA45 matematikk, 9.5.4 Oppgave La fx, y, z) xy + arctanxz). La P være punktet,, ). a)
Randkurva C til flata S orienteres positivt sett ovenfra, og kan parametriseres ved: r (t) = [ sin t, cos t, sin t] dt, 0 t 2π.
Ma - Løsningsforslag til uke 17 i 7 Eks. mai 1999 oppgave 4 ylinderen x + y = 1 skjærer ut ei flate av planet z = x + 1 dvs. x + z = 1 med enhetsnormal i positiv z-retning lik n= 1 [ 1 1]. Flata blir en
(t) = [ 2 cos t, 2 sin t, 0] = 4. Da z = 2(1 + t) blir kurva C en helix/ei skruelinje på denne flata (se fig side 392).
Ma - Løsningsforslag til uke 5 i 7 Eks. mai 994 oppgave Romkurva er parametrisert for t [, π] ved r (t) = [ + cos t, + sin t, + t ] Hastighets- og akselerasjonsvektorene blir v = r (t) = [ sin t, cos t,
Løsning, Stokes setning
Ukeoppgaver, uke 4 Matematikk, tokes setning 1 Løsning, tokes setning Oppgave 1 a) b) c) F x y z x y z F x x + y y + z z 1+1+1 iden F er feltet konservativt. ( z y y ) ( x i z z z ) ( y x x x ) k i +k
Løsningsforslag MAT102 Vår 2018
Løsningsforslag MAT102 Vår 2018 Universitetet i Bergen Det matematisk-naturvitenskapelige fakultet Eksamen i emnet MAT102 Tirsdag 12 juni 2018, kl 0900-1400 Oppgavesettet har fem oppgaver Hver deloppgave
Høgskolen i Oslo og Akershus. e 2x + x 2 ( e 2x) = 2xe 2x + x 2 e 2x (2x) = 2xe 2x + 2x 2 e 2x = 2xe 2x (1 + x) 1 sin x (sin x) + 2x = cos x
Oppgåve a) i) f(x) x e x f (x) ( x ) e x + x ( e x) xe x + x e x (x) xe x + x e x xe x ( + x) ii) g(x) ln(sin x) + x g (x) sin x (sin x) + x cos x sin x + x tan x + x b) i) Sidan både teljar og nemnar
Fasit til utvalgte oppgaver MAT1110, uka 11/5-15/5
Fasit til utvalgte oppgaver MAT0, uka /5-5/5 Øyvind Ryan ([email protected] May, 009 Oppgave 5.0.a Ser at f(x, y = (, 3, og g(x, y = (x, y. g(x, y = 0 hvis og bare hvis x = y = 0, og dette er ikke kompatibelt
UiO MAT1012 Våren Ekstraoppgavesamling
UiO MAT1012 Våren 2011 Ekstraoppgavesamling I tillegg til eksamen og prøveeksamen fra våren 2010 inneholder denne samlingen en del oppgaver som er blitt gitt til eksamen i diverse andre emner ved UiO i
Eksamen AA6524 Matematikk 3MX Elevar/Elever AA6526 Matematikk 3MX Privatistar/Privatister. Nynorsk/Bokmål
Eksamen 05.12.2007 AA6524 Matematikk 3MX Elevar/Elever AA6526 Matematikk 3MX Privatistar/Privatister Nynorsk/Bokmål Oppgave 1 a) Deriver funksjonen: f x 2 ( ) = cos( x + 1) b) Løs likningen og oppgi svaret
Eksamen IRF30014, våren 16 i Matematikk 3 Løsningsforslag
Oppgave 1. Eksamen IRF314, våren 16 i Matematikk 3 Løsningsforslag Ellipsen vil skal finne er på standardform x a + y b 1 der a > b for styrelinjene er vertikale linjer. Formelen for styrelinjene er x
Oppfriskningskurs i matematikk 2008
Oppfriskningskurs i matematikk 2008 Marte Pernille Hatlo Institutt for matematiske fag, NTNU 4.-9. august 2008 Velkommen! 2 Temaer Algebra Trigonometri Funksjoner og derivasjon Integrasjon Eksponensial-
Løsningsforslag. Innlevering i BYFE 1000 Oppgavesett 1 Innleveringsfrist: 10. oktober klokka 14:00 Antall oppgaver: 6. Oppgave 1
Innlevering i BYFE 1000 Oppgavesett 1 Innleveringsfrist: 10. oktober klokka 14:00 Antall oppgaver: 6 Løsningsforslag Oppgave 1 x 1 +6x +x 3 = 8 x 1 +3x = 3x 1 +9x +x 3 = 10. a) Totalmatrise: 6 1 8 1 3
Alle svar skal grunngis. Alle deloppgaver har lik vekt.
Alle svar skal grunngis. Alle deloppgaver har lik vekt. Oppgave Vi denerer matrisene A, B, og C som A = [ ] 3, B = 5 9, C = 3 3. a) Regn ut følgende matrisesummer og matriseprodukter, om mulig. Dersom
UNIVERSITETET I OSLO
UNIVERSITETET I OSLO Det matematisk-naturvitenskapelige fakultet Eksamen i: MAT Kalkulus og lineær algebra Eksamensdag: Lørdag 25. Mai 29. Tid for eksamen: :5 4:5. Oppgavesettet er på 7 sider. Vedlegg:
y = x y, y 2 x 2 = c,
TMA415 Matematikk Vår 17 Norges teknisk naturvitenskapelige universitet Institutt for matematiske fag Løsningsforslag Øving 9 Alle oppgavenummer referer til 8. utgave av Adams & Essex alculus: A omplete
SIF5005 Matematikk 2, 13. mai 2002 Løsningsforslag
SIF55 Matematikk, 3. mai Oppgave Alternativ : At de to ligningene skjærer hverandre vil si at det finnes parameterverdier u og v som, innsatt i de to parametriseringene, gir samme punkt: Vi løser hver
Oppgaver til seksjon med fasit
Oppgaver til seksjon 4.-4.5 med fasit Oppgaver til seksjon 4.. Finn alle løsningene til ligningssystemet x + y z = x + y z = x + y + z =. Finn alle løsningene til ligningssystemet x y + z = x y = 4 x +
Eksamen R2, Våren 2011 Løsning
R Eksamen, Våren 0 Løsning Eksamen R, Våren 0 Løsning Del Tid: timer Hjelpemidler: Vanlige skrivesaker, passer, linjal med centimetermål og vinkelmåler er tillatt. Oppgave (8 poeng) a) Deriver funksjonene
Oppgave 1 (25 %) - Flervalgsoppgaver
Oppgaver og løsningsforslag for 4t eksamen 10.mai 006 i LO510D Lineær algebra med grafiske anvendelser. Fra og med oppgave skal alle svar begrunnes. Oppgave 1 (5 %) - Flervalgsoppgaver Denne oppgaven består
være en rasjonal funksjon med grad p < grad q. La oss skrive p(x) (x a)q(x) = A
MA 4: Analyse Uke 46, http://homehiano/ aasvaldl/ma4 H Høgskolen i Agder Avdeling for realfag Institutt for matematiske fag Oppgave 73: Først skal vi delbrøkoppspalte (se Eksempel 5 side 558 i boka) 3t
Matriser. Kapittel 4. Definisjoner og notasjon
Kapittel Matriser Vi har lært å løse et lineært ligningssystem ved å sette opp totalmatrisen til systemet gausseliminere den ved hjelp av radoperasjoner på matrisen Vi skal nå se nærmere på egenskaper
Oppgavesettet har 10 punkter 1, 2ab, 3ab, 4ab, 5abc som teller likt ved bedømmelsen.
NTNU Institutt for matematiske fag SIF55 Matematikk 2 4. mai 999 Løsningsforslag Oppgavesettet har punkter, 2ab, 3ab, 4ab, 5abc som teller likt ved bedømmelsen. i alternativ (3, ii alternativ (2. 2 a For
Løsningsforslag, eksamen MA1103 Flerdimensjonal analyse, vår 2009
Norges teknisk naturvitenskapelige universitet Institutt for matematiske fag Side 1 av 8 Løsningsforslag, eksamen MA1103 Flerdimensjonal analyse, vår 2009 Oppgave 1 Avgjør om grenseverdiene eksisterer:
Vår TMA4105 Matematikk 2. Løsningsforslag Øving 2. Norges teknisk naturvitenskapelige universitet Institutt for matematiske fag
TMA415 Matematikk 2 Vår 217 Norges teknisk naturvitenskapelige universitet Institutt for matematiske fag Løsningsforslag Øving 2 11.1.9: Den aktuelle kurven er gitt ved r(t) (3 cos t, 4 cos t, 5 sin t).
Anbefalte oppgaver - Løsningsforslag
Anbefalte oppgaver - Løsningsforslag Uke 6 12.6.4: Vi finner først lineariseringen i punktet (2, 2). Vi har at Lineariseringen er derfor 2x + y f x (x, y) = 24 (x 2 + xy + y 2 ) 2 2y + x f y (x, y) = 24
Fasit til eksamen i emnet MAT102 - Brukerkurs i matematikk II Mandag 21.september 2015
Fasit til eksamen i emnet MAT02 - Brukerkurs i matematikk II Mandag 2.september 205 Fasit. (a) Løs ligningssystemene. i) 5x + 7y = 4 3x + 2y = ii) 3x + 4y + z = 2 2x + 3y + 3z = 7 Svar: i) x = 85/, y =
Fasit til utvalgte oppgaver MAT1110, uka 8-12/2
Fasit til utvalgte oppgaver MAT, uka 8-/ Øyvind Ryan [email protected] February, Oppgave 3.3.6 Vi har funksjonen fx, y, z xyz og kurven Vi ser at rt e t, e t, t, t. vt e t, e t, vt e t + e t + frt t. e
Eksamen, høsten 14 i Matematikk 3 Løsningsforslag
Oppgave 1. Fra ligningen Eksamen, høsten 14 i Matematikk 3 Løsningsforslag x 2 64 y2 36 1 finner vi a 64 8 og b 36 6. Fokus til senter avstanden er da gitt ved c a 2 + b 2 64 + 36 1 1. Dermed er fokuspunktene
4 Matriser TMA4110 høsten 2018
Matriser TMA høsten 8 Nå har vi fått erfaring med å bruke matriser i et par forskjellige sammenhenger Vi har lært å løse et lineært likningssystem ved å sette opp totalmatrisen til systemet og gausseliminere
MAT 1110 V-06: Løsningsforslag til Oblig 1
MAT V-6: Løsningsforslag til Oblig Oppgave : a) Antall sykler i stativet X rett før påfyllingen i måned n + er lik 4% av antall sykler i X måneden før, pluss % av antall sykler i Y måneden før, pluss %
Løsningsforslag til prøveeksamen i MAT1050, vår 2019
Løsningsforslag til prøveeksamen i MT15, vår 19 Oppgave 1. a) Vi har sinx + y) d R cosx + y) sinx + π) + sin x siden alle fire leddene er. yπ y π dx sinx + y) dy dx cosx + π) + cos x) dx sin π + sin π)
y (t) = cos t x (π) = 0 y (π) = 1. w (t) = w x (t)x (t) + w y (t)y (t)
NTNU Institutt for matematiske fag TMA4105 Matematikk, øving 7, vår 013 Løsningsforslag Notasjon og merknader En vektor boken skriver som ai + bj + ck, vil vi ofte skrive som (a, b, c), og tilsvarende
Løsningsforslag til utvalgte oppgaver i kapittel 10
Løsningsforslag til utvalgte oppgaver i kapittel 0 I kapittel 0 får du trening i å løse ulike typer differensialligninger, og her får du bruk for integrasjonsteknikkene du lærte i forrige kapittel. Men
Løsningsforslag. og B =
Prøve i Matte EMFE DAFE ELFE BYFE Dato: august 25 Hjelpemiddel: Kalkulator og formelark Alle svar skal grunngis. Alle deloppgaver har lik vekt. Oppgave a) Gitt matrisene A = 2 3 2 4 2 Løsningsforslag og
Kjeglesnitt. Harald Hanche-Olsen. Versjon
Kjeglesnitt Harald Hanche-Olsen [email protected] Versjon 1.0 2013-01-25 Innledning Kjeglesnittene sirkler, ellipser, parabler og hyperbler er klassiske kurver som har vært studert siden antikken. Kjeglesnittene
Løsningsforslag. Innlevering i BYFE/EMFE 1000 Oppgavesett 1 Innleveringsfrist: 14. september klokka 14:00 Antall oppgaver: 3.
Innlevering i BYFE/EMFE 1000 Oppgavesett 1 Innleveringsfrist: 14. september klokka 14:00 Antall oppgaver: 3 Løsningsforslag Oppgave 1 a) ln a ln 3 a+ln 4 a = ln a 1/2 ln a 1/3 +ln a 1/4 = 1 2 ln a 1 3
MA1102 Grunnkurs i analyse II Vår 2019
Norges teknisk naturvitenskapelige universitet Institutt for matematiske fag MA1102 Grunnkurs i analyse II Vår 2019 Først en kommentar. I læreboka møter man kjeglesnitt på standardform, som ellipser x
Kapittel 10: Funksjoner av flere variable
0.. Introduksjon til funksjoner av flere variable 95 Kapittel 0: Funksjoner av flere variable 0.. Introduksjon til funksjoner av flere variable. Oppgave 0..: a) Den naturlige definisjonsmengden for f(x,
Notater nr 9: oppsummering for uke 45-46
Notater nr 9: oppsummering for uke 45-46 Bøkene B (læreboken): Tor Gulliksen og Arne Hole, Matematikk i Praksis, 5. utgave. K (kompendium): Amir M. Hashemi, Brukerkurs i matematikk MAT, høsten. Oppsummering
Løsningsforslag. Prøve i Matematikk 1000 BYFE DAFE 1000 Dato: 29. mai 2017 Hjelpemiddel: Kalkulator og formelark. Oppgave 1 Gitt matrisene.
Prøve i Matematikk BYFE DAFE Dato: 29. mai 27 Hjelpemiddel: Kalkulator og formelark Løsningsforslag Oppgave Gitt matrisene A = 2 2 B = [ 2 3 4 ] og C = Regn ut, om mulig, summene A + B, A + B T og A +
Høgskolen i Oslo og Akershus. a) Finn den deriverte av disse funksjonene: b) Finn disse ubestemte integralene: c) Finn disse bestemte integralene:
Oppgave 1 a) Finn den deriverte av disse funksjonene: i) f(x) = x x 2 + 1 ii) g(x) = ln x sin x x 2 b) Finn disse ubestemte integralene: i) (2x + ) dx ii) 6 cos(x) sin 5 (x) dx c) Finn disse bestemte integralene:
MAT 1110: Bruk av redusert trappeform
Tom Lindstrøm 10/5, 2006: MAT 1110: Bruk av redusert trappeform I Lays bok brukes den reduserte trappeformen til matriser til å løse en rekke problemer knyttet til ligningssystemer, lineærkombinasjoner,
Matematikk 1 Første deleksamen. Løsningsforslag
HØGSKOLEN I ØSTFOLD, AVDELING FOR INFORMASJONSTEKNOLOGI Matematikk Første deleksamen 4. juni 208 Løsningsforslag Christian F. Heide June 8, 208 OPPGAVE a Forklar kortfattet hva den deriverte av en funksjon
UNIVERSITETET I OSLO
UNIVERSITETET I OSLO Det matematisk-naturvitenskapelige fakultet Eksamen i MAT-INF 00 Modellering og beregninger. Eksamensdag: Torsdag 6. desember 202. Tid for eksamen: 9:00 3:00. Oppgavesettet er på 8
TMA4110 Eksamen høsten 2018 EKSEMPEL 1 Løsning Side 1 av 8. Løsningsforslag. Vi setter opp totalmatrisen og gausseliminerer: x 1 7x 4 = 0
TMA4 Eksamen høsten 28 EKSEMPEL Løsning Side av 8 Løsningsforslag Oppgave Vi setter opp totalmatrisen og gausseliminerer: 2 2 2 4 2 6 2 4 2 6 2 2 Dette gir likningene og 2 2 4 2 6 7 2. x 7x 4 = x 2 + 2x
