CSE
chpt4 An Application numerical integration

Art of Parallel Programming

Info icon This preview shows pages 1–8. Sign up to view the full content.

Image of page 1

Info icon This preview has intentionally blurred sections. Sign up to view the full version.

Image of page 2
Image of page 3

Info icon This preview has intentionally blurred sections. Sign up to view the full version.

Image of page 4
Image of page 5

Info icon This preview has intentionally blurred sections. Sign up to view the full version.

Image of page 6
Image of page 7

Info icon This preview has intentionally blurred sections. Sign up to view the full version.

Image of page 8
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ,« ‘ _ CHAPTER 4: New T}-1AT WE KNOW Haw TO SEND MESSAGES with MP1, let's write a px'agram that uses 1116332138 pafising to soéw a prohiem: calculate a definiie .integrai mm the :rapezaidal mic. If "you remfimher the Impemidai mite, Wu can skip secticm 4.}. The Trapezaida: Rule Recali mat the definite tmegmi [mm a m b of a nozmegative function f(x) can be thought of as the area bmmded by the Ara-axis, the vertical lines x =2 :1 ans} x m 2.7, and the graph of the {unciimn fix), See Figure 4.1. One approach u} emulating; this area 01' integrai is to parzitimz the region into reguiéér gemnetric sheaves and then 3:35] the areas 0f the shapes. In the zmpemidal rule, the reguiar geometric Magma are trapemids; each trapezoid has its base an the xwaxisj veriical sides, and its Mp edge mining tam paints {m the. graph of fix}. See Figure 4.2. For our pumoses, we’ll. choose an the $05393 to have me same length 80 if there are n'tra.1:792:uids, the base of each Wiii in: ft (h min. The base {3f the. lefmmst {rapemid will be. {he interval {ma + h}; the base of the next. trapezoid will be it: + 31,51 + 2h}; m nexi, [a + 2h.,(1 + 322}; etc. In gemm’l, the base of fine I'm trapemfid will be {a + {5' w 1}h,a +- 571], i w 2., , a. In Grder £0 simplify notation, is: Big deflate a ~+~ :11, z’ D, , n. ’I‘hen the lengih of the left side of. the am {rape-5mm wfil be? fng a}, and. its; right side wifl be {m}. Sea Figure Thus, the area of the it}; trapezmfl Wm be 5'3 54. Simmer 4mm. Appiz’mrian: Ntin'wr'z'ml Irdegmiifin y A Definite integrai of a nannagmive function (I! 43 The'fiapezmdalRuw 5 EMHMM)[email protected]* anti the area of am" entire amimximafmn will. be the sum of rm: areas of the trapezohjm éfiflmi+flmfl+%Mfim}+fl&fl+~'+§Hflfiw}+flmfi :3“ “Ewmg+yua+mun+~~+flwn ="fi/a)f2 + fixn}f2 +‘f{x}) +‘f{xsl *'-“~ + f{Xn»:}}h‘ So by putting fix} into a smbpmgmm, we cm write a serial program for caiaulating ax: integi‘al using the [trapezmdal rule, X* Caiculate definite integra1 using trapezoida? ruTe. * The fuaciisn fix} 15 hardwired. * Input: 3, b, n. * Umtput: estimate of integraE from a to b of f{x} * using n trapezoid5u */ #inaiude <$td10.h> maint} { f3oat éntegrai; /* Stare resuit fin integra? */ fYOat a, b: /* Left afld right endpoints *f int n; /* Number 0? trapezoids */ flgat h; /* Tragezaid base width '*1 f1aat x: int i; fEGat {Eflaat x}; f* Function we’re fintegrating *2 printf(“Enter a, h. ana n\n"}: scanf{"%f %f %d”, &a. &b, &n): h w Eb~a)ln; €ntegra1 * (fie) + f(b})/2.0: x m a; for {i w 1: 5 (w h~1: i++3 { x u x + h; integral m integraI + fix): } integra? m integra1*h; printff"with n w %d trapezoids. our estimate\n". n}; prénif{"9f the integrai from %f in %f w %f\n". a, b, integral); } E* main */ ..........__._.__._.‘.,..,.v .. .. “MWHMM Chapter ELM—An. Appfimrz’an: Nmnerzimf Irziegzzmmn f3gat f€f10at x} { Fant returnmvalg /* Caltulatg fix)‘ Store: ca'iczflation in r‘etarnmvak “W return retm‘rxmvai‘; 1} N“ f */ Famileliziag the Trapamidal Rifle As; we saw in (31'2.e:pm1' .2, there are several approaches in paraflelimng 55 SE“- réal gmvgmm. Perhaps 1mg simplest appmach dimribtjtes; me {jam ,amnng the pmaesses, am? each pmcess mm esgeentially Um same pragmmm: its; Share 6f the data 1;: our case, the data is just the interval {mill am? the number 0f trapezoids n. 80 we can paz'aliehze the zrapewidal rule: mogmm by assigning a suhimervai of hi, Z?) to 9am process. and having-z; that promfis estimate the integral off over {he summervai. In gram to calculate the integra} aver Ea, bL the pramessws’ incal czalcruia‘tiuns are added. An mbvia‘ms quegtian here- is, E-‘mw does 9am pxrncess know which subjm 't‘erval it 312mm imegral‘e over, and how many tragmzoids it should use? in order ta answer this, Suppase there are p processes; and n: trapemidg, and, in raider :0 Simplify the damaging}, aésa suppme that 11 is avwly divisible by p; Then it is rmtuml m;- ihe first process to calculem {he mm 01'. [he first 52/}? trapezoids, {he secemi precess to mimlale the area of the new rzfp, etc. Recall Hm: MP}. iciemifies gash process by a ncmnegara‘ve inmgez: Sn if there axe p processeg, the firm is; 133115959. {3%, ihe second precass 1, . . . , 93116 $119 lass: pl‘acrmss p -~ 1. Using {.I.3{2~.11¢3ta.t1'<13n we devemped in Our discussion 0f the Serial program“ we have each pmcess caimlaling integrals (we: the Subimm'vals {I'Ldid‘ated in Table 4. L “£11115 each pmcess needs the fmlawing infatuation; 4,2 Parallefizmg the ’fiapezmidai Rub: a The number m" processes, #3 at Rs rank u‘ The entire interva} 0f imegm’gion, {L1, 2)} a The number of subimermls, 32 Ram}: {mm Chapter 3 21m the first two items can be found by calling fhe MP1 funcuons MPLHCOmmwsize and.MP1mCGmmmrank. ThelaatIWMaRenm flunfld probably be input 333' the amen But this {'perl‘laps surprisingly) {fan misc-3 same dfificuh pfohkfins. 50 RH ourfhstafieuufi aicakxflafingthe Huegnfl.}eY5 “"imrdwére" theme values by simpiy setting zjkwir values with assignment state" mentfi. A secend mbvima question is, Haw me incfividual pmcesaes’ micula» {mnwm&fluw(NewmgmmWMMamxdeMMMhemamfiexhpmmfis RTSuiE to, say. process 0, and have prowess; 0 do the finai addiiimm With these assut‘ngnions we can write our firSt “meal” MP? pregram. Paralle f* I Trapéxoidai Ruie it * Input: None. * Output: Estimate 0? the integr&1 from a to b of f(x) * usifig the trapezeida] rufie and n trapezmids. * * Aigorithm: * 1. Each pracess calcu1ates "fita" ifitervaT of * integratéon. * 2 Each process Estimates the integra1 of ftx) * over its intervaT using the trayezoidal pale. * 3a. Each process km 0 sends its $ntegra1 t9 0. * 3b. Process 0 sums the calculatfioms received from * the indivédua} pracesses and prints the resu1t. 1f: . * Note: fix), a, b, and n are a1? hardwirafi. 'kff #Mc? ucie <3td'ic3.h> H We“?! be using MP1 mutines, definitions, EtC. */ #inc‘éade "mm .h" mainiint 6 int int ffioat flaat int ¥?Gafi flea? r93. char” argv) { mymrank: f* My gracess rank 9; f* The number of processes a fi-G.G; /* Left endpsint b m 1.0; 1* Right endpoint n m 1323; /* Number of trapezoids h; /* Trapezoid base Iength éocafwa; /* Left endpoint fig pracess *g’ *1 *r’ U *f if *f 58 Cimprer 4~~~An Applimzztmn: Nz‘m‘zer'z‘mi frzzegratian figét 19ca3fib; f* Right endpoint my process *! int iocalwn: /* Number of trapezoida far *f /* my caifluTation *f fiaat integra1; f* ?ntegra} Over my intervai */ fleat tata}; /* ¥0taf integra? */ int gaurce: f* Prueess sending éntegra? *3 int éest w G: /* A?1 messages go to O *! int tag w G: MPIWStatUS Status: fTDat Trap€f1aat Tocaima. {ant IocaTmb, fint 1oca1mn. fioat h); f* CaiCUWate 106a? integral */ /* Let tfie aystam do what it needs to start up MPE */ MPIWInit(&argc, aargvfi; /* Get my pFOCéfifi rank *f MPIWCO m rankiMPIWCGMMWWDRLD, &my rank); /* Find out how many processes are bafng used *I MPIMCommmsi29(MP1WCDMMWWORLU, &§); h w (b'a)fn; f* h is the same far a}? pracesses *X 10ca3mn w nip; f* Se $3 the number of trapezfiéds *f f* Lengfih of each procass’s interva? cf * integration a locaTwn*hA So my interva1 * starts at: *i locaT a fl a + mymrank*10ca1mn*h; Toca? b m Wocal a + Essa? n*h; fntegrai m Trapiimcafma; local h. Eocaimn, h): /* Add up the integr63g caicu3a€ed by each prucess */ if imy_rafik w“ Q) { tota? # integra1: far (auurce m l; $our£e < p; scurce++) { MPEMRecvcaintégrg}, 1, MPIMFLUAT. sugrce, tag. MPEWCQMMWNQRLB, &5tatus}: tota] m tmta} + finiegra}: } } e§se [ MPimSend(&éntegra1, 1. MPImgLDAT, dest. t&g. MPIMCGMMMNDRLS}: .} f* Print the resu1t *f if {myfirank mm G) { “ printf{"W?th n % %d trapezoids. cur estimate\n”. n): 4.2, Paralielizmg the Trapezoicfiat Rule printf{“of the integral? from 93? to 2;? m S'éfln". & _ a, b, Mata“; 1* Shut down WI *1 MPIWFinaHzeCE: } /* main *! float Trapf float "ioca‘lma N “in *f, float Mmhflb /‘* in W, in: Woca1w_n /* in *7. oat h' N in *i’){ float mtegr‘al: 1”“ Store remit in integral *l float x; “int 1‘: float flfleat x"); M funch We're integrating W integra] w (filocalwa) + filacalwb})f2.0; X ‘1" 10ca3ma; for (i w 1; 1 <« Eoc&1mn~l; i++j { x w x + h: integra1 w integral + f{x); } integra1 w integra1*h; return integra1; } 1* Trap */ float Hfloat x) { float returnmvah /* Calcuiate fix}. *f /* Stare calculation in returnmvah W retum returnwvah } /* f */ Observe that this program 3150 uses the SPMD paradigm. Even though garocesg 0 executeg an eagemiafly :‘iiffereut set of mmmands fmm the remaining processes, it :5in runs the same pz'agmm, The different commam‘is are executed by bxranchifig based on the process rank. Aim miss that we were carequ {0 dimingu‘igh betweesz variabies whase contents were significant on all the processes, and variables whose contents Mi».ufléméwmfimWmfiMAmafimflzmmmMismmwnmmmem . . ESQ (Simmer aim/fin Appfirmim: Nanny-{inf Imegrrzzion were {mix} signifimm on ind‘mdna} pi‘{7{{?SSEFS. {ix‘an'ipies of? {he former are a, b, and n. Exampies ("If fhe latter are 101::a17wa, 10ml}, Mid 10ca'i____n. Vari» ables wimse Hummus are sigflificam on all the mace ‘s are Sometimea (failed globaé variables, and variahws wl'mzae cements am $ég§11ificam oniy (31's indévit‘j» uai pmcesseg am sametimes (talked local variabkes. If 3mm {earned to pregmm in 'Pasml, this, ierminuiogy may at first seem .Somwhax cctmfusing I-Iowwen its usmaily very may :0 icaii from {he mnmxt which meaning is Ez'nphed. It’s extremely ifnpm’th that we, as; programmers, distinguish between global}. and Eucai variablefi: it can be WW difficult: or impomible m decipher a program that makes; m} distinction hetwem the 1mm One 0f the must insidious thmgs a pairaiiai programmer can {it} is m {me {he same vaymbie in? both g§0bal and Ema} swinger wiih 1m L'Eaaruxnwtméon. m genwah ssepamte variables :flmuld be a‘iimtened J'm‘ glam! and meal scalar variables. Em composite variables it may be. newmary '11} use iihe {same stmage far both glahal and iocal variabieg. Plowman if this 13 (Sum, it sfimum has: sieariy dualsmemcd. UT} on Parana. Systems 0m Dav-mus problem with our pmgram is its hm 0f generality The funmim, fix), and {be input. data, 51,6). mm 52. are 'i‘ia'rriwiaied. 5:3 if we want is change any of these, we mum ecih and mcm‘npiée the pmgmm. Different functirang 0311 ms nacm’pamed by revising me Trap functmn rm {hat it takes an additional 1Jai'ametelvwfl perinatal? m a functémzz. Since this has nothing to do with paraiiel cm‘npmtmg. we'i} leave it. 33 an exercise m mutiify‘ the program it) me funciirm painters. Hewaver. ah? issue 131' c§3angh3g the input data has everyflximg to do with pamiiei crmngmzmg. 59 we 521mm take a 160k a: it“ In 0111' gr‘émtingg and Saris} trammidaé 132755233113 weassmned that pmcess {3 could [tenth read {mm steward inpm [the ke‘ybmrd} and write to smmiard oumut ('th terminal: screen). Many parailel sygiems provide miss much 1/0. In faci, many parailei systems 5:11am? all pzucesmrg to bow read imm alarzdard ianIi and write m standard mitpiil. So what’s the pmblem? In {Em first place, we wen-2 cgrefui to say “many” {th “all”? systems pm wide this much {/0. But evm if we could “an,” there wmud still be issues that need m be @301erde Let’s lack an an exanufie. Suppose we .z‘miwdif‘y the trap/emf ("3&3 pragmm so {hat each momma mmmpis £0 {ta-3d the values :31, b, and n by adding; the smexmm .Scat1€’(“%f “xéf “2%”. EM, £33. 8m}; Suppose aiso that we mm the pmgra‘un Wiih two protlflsses and the user {3/3368 in 15‘ G ‘i 1034 ...
View Full Document

  • Fall '06
  • Baden

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern