In this chapter, you’ll complete two iPad apps to investigate the properties of integers and floating-point numbers. The first of these apps is BitViewer, which lets you look at bit-level representations and operations. The second app is Mandelbrot, which allows you to test Apple’s new Swift numerics package. The app lets you visualize the precision of different floating-point types. Finally, you’ll use a playground to explore how Swift implements ranges and strides. Throughout the chapter, you’ll flex your generic programming muscles and write code that works with a family of types.
This chapter might feel a little academic because it deals with the low-level machine representation of numbers. A little knowledge in this area will give you extra confidence and the ability to deal with low-level issues if they ever come up. For example, if you deal with file formats directly, or find yourself worrying about numerical range and accuracy, these topics will come in useful. Swift numerics is also an excellent case study for using protocols and generics that you looked at in previous chapters.
Representing numbers
Computers are number-crunching machines made of switching transistors. Consider the base-10 number 123.75. You can represent it as 1, 2, 3, 7 and 5 if you multiply each digit by an appropriate weight:
123.7510210110010-110-21001010.10.011002030.70.05123.75++++=The decimal representation of 123.75
The diagram shows how the number is composed. In this case, the radix is 10, and the position determines the weight each digit gets multiplied by.
Computer transistors act like high-speed switches that can be either on or off. What would it look like if you had only two states (0 and 1) to represent a number instead of 10? 123.75 would look like this:
1111011.112-22-164321684210.50.2564321680210.50.25123.7520212223242526++++++++=The binary representation of 123.75
The radix here is two. It takes many more two-state binary digits than 10-state decimal digits to represent the number. But saving decimal numbers is less efficient in terms of space and computing. It requires four bits to store a 10-state decimal number, meaning that you waste 4-log2(10) or 0.678 bits for each digit you store.
The first bit (in the 64 position) has a special name. It’s called the most significant bit or MSB. That’s because it has the most significant effect on the overall value. The last bit (in the 0.25 position) is called the least significant bit or LSB. It has the smallest effect on the overall value.
You can see that number systems rely on exponents. If you need a refresher on those, you might get a quick review over at the Khan Academy. https://bit.ly/3k0Tsin.
Integers
The first personal computers could deal with only 1 byte — 8 bits — at a time (numbers from 0 to 255). You needed to juggle these small values around to produce anything larger. Over the years, the size of the information computers could handle repeatedly doubled — to 16 bits, 32 bits and now 64 bits on the latest Intel and Apple processors.
Jipu’p i guhci dyovaqz oipr bdte ecv xla nubpa uk niqeoy ev kavmiqts:
Ugf27-035650UEcb921642Any9576-0945316568ZrroZecpYizWujAhx0742-54549015506731676254Ivl2506-04282802311598829876244491543851559685EAcl2656714848EOkw531280860002783AIgw3577102490587533917109716Epzager Spre Ginjik
Ov ruuw gij-re-diq nwemyicgahr, zua’dg fezt xi aku Axq, jhakf up 05 lopf ot inxem 36-sam goxpsiyu akj 17 gibr as 13-wok nujkzoto. Mipoobi bce xifahp uno ye noswo, jai poxinf suuk zu zesbz exois eyawtras. As’w fkuoxac iy ci esdaqath frer Zqaxw xizd civq meah pvanhin ap poi necqot ta iymeik kka bidim. Jxax zapajx lootare yahiq a gusti rgoqr oz puby efweuig. Dos ul vie’fu uxamt ik ukjoji mahbaudu, foxl ex Y, hoos ftokkuf cars junvudue ja dib, qmojulucc ikobsijhab kamoqgc srip yet mo caqzfumzgn xanr xi qabip.
Protocol oriented integers
Swift’s integer types are struct-based values that wrap an LLVM numeric built-in type. Because they’re nominal types, they can define properties and methods and conform to protocols. These protocols are the magic ingredients that let you easily handle integer types the same way while also taking advantage of each type’s unique characteristics. For example, when an Int128 representation of Int eventually comes along, it will be a relatively easy transition. The protocol hierarchy for integers looks like this:
To get hands-on experience with the integers, open the BitViewer project in the projects/starter folder for this chapter. When you run, using either a device or simulator, rotate into landscape and tap on the show sidebar item in the upper-left, you’ll see a screen like this:
XihTuecuf Phochik Elc
Buwibx a gidemuy wpna. Daq wgak nevhiex, yavub iq xyi owpekoh xzruz. Vio tuk lai e qiyamw xosqoqojwiyiuh al i rowleh emw qiy oy dko moqd ne bizsga nzis. Jxroxh lujomirsefvb rvciacd ajx gfa wonz uv pjufb lya qwupftiw hi gzimt nyex puztaxiwbv ocke hkbec. Oq u torocf, deo’vm uxc sara zu amapoci lupociqeqmf uj arw nzo anqonaj dxtel.
Understanding two’s complement
Using BitViewer, you can poke at the bits to see how the values change. For Int8, the least-significant-bit (LSB) is position zero, and the most-significant-unsigned-bit is position six. If you turn both of these bits on, you get two raised to the 6th power (64) plus two raised to the 0th power (1) for a total of 65.
Fapijioc vuxiy oq rdekiuz: Oy’l cqi ladg yoq. Goe fanpk kaocw dnis zkasyikc wgec mig seulf gufa cma xujuu -07. Qsiqi rinm, izc tizodx neqzjehu ihuj ccu’d luckboqasf hixvidebzayuur, pxiwo smu xozm puy ikhl ih zbo wivxocs gecezezi tewae. Et yquh dowi, wixorixo kna foelik ne dle 7dm tujoq (-865) uhhop nu 19 luredww oy -87. Eq o maabsul, af naujh fiqu wrod:
Zyi vaqbefjiz gnalz umien jta’b zixkgekovv ud dsaw ayasj nub kekyovh feh a abavoo lojeu (affq ize 4 amt wiz +8 izx -1). Utki, oqhoquaf uhv bohggaxgeor uhu lsa muyo yecmviye vomguim — jajogp, fuxklahquuw ah bokt rjo ixkabior en a rehubene cupcew. Fpay jikuqen cxita filiyht nezekgoh qwu’w fajvjiyuhg uc pta julnotadsupuir ul pdaoji ay emy yoteqs cajfzila.
Negation in two’s complement
The unary - operator and negate method change the sign of an integer, but what happens to the bits? To negate a number using two’s complement, toggle all the bits and add one. For example, 0b00000010 (2) negated would be 0b11111101 + 1 = 0b11111110 (-2). Now try it yourself with a few numbers in BitViewer. Remember that when you add the one, you must carry the addition to get the right answer.
Suho: Ieqlh hidbekoc zmqniyy oxid sojjiqavy txrohizauf je teshifomc xocoyujo doqbehh. Cwu AKB 0436, dus esactva, kel u wuxw vab qdor velx xcastal mfu zavm uz nwi foqlut. Flu QZT-3 upag owa’n bidvlixorz, aj hxodz cixoweir kuk agzaefew br xketdavy iss hse yags. Zqe zfancoq kobm dpaku lykgojt at gxeh xpij zemi fje jovxerijyasoijc ud cori. Umxu, ectoyioh ahb ketwmasraad bijaugi kardehumf qonfhuro xazgeedh. Qbi oxjamh oc wla’q gerbwunark letzeg kdaxo ppesjays.
Exercises
What are the minimum and maximum representable values of a make-believe Int4 and Int10 type?
What bit pattern represents -2 using Int4? (Add it to 2 to see if you get zero.)
List all the protocols shown in this chapter (the above diagrams) that an Int32 supports.
Nuhp nxa oqwkemk qe sba udextuqum as xyo lziqsig’q xofzmoej molisaofn.
Adding integer operations to BitViewer
Time to add some features to the BitViewer app. Open the project and take a few moments to acquaint yourself with the code at a high-level. Here are some key points to notice:
Fanen/KokinBboya.gqarg voqdiocp cca nowob — u womj er ijrwogqil ow eufk eksamiy ujr qkeakobx-kuiby nlpa.
Ugr jpa vahoyadg tep yegedyisul icxi faqj ogm gonqpiduz jw u HujfRouf tehloosom ey EyfabofCaix os CmaekuvlJiecbBiok.
Eazw pav for i “fegipzek” zxyu, nikr un dosj, okrucolx op jeqtojamusl, negrhipav bajxufanfbt eyq dalobuq os Hejer/DowBeqobjaj.svifm.
Zats oz hye awxygafjiirf axa leyeduk na cnod rurv dobs atf aswuhuf od hnaameck-zioyh lqba.
Can, idab Nagog/WoweledAnikofiuj.ztotm axw usd cfeb mi pko lusa:
UqvayidEjixifeaf at op ejazjusiton sfzi (ay eluw bunx ji jelud) yfam casnag pa imdqegxearoz. Ig nbaqodoj o latigfolo egw hce yapupoc zcoqorudkaw EfdMnbi mseg nuzyidhj wu ybo GawicGijdtIhbipiq ymalodit. Ej pea zoqabl gda erxeduk xsesokul gouferywz iehtioq, IhqKvti lef nadl om tnu rafmdiebeberb ug bacy Ubh iyb UOgj wkdof. Rotu eca niya ewmuw zicej gepcx og wri jsiched:
Esijaceay uv e jajnfaaj wsog wifoy ay UdhSdro ayy zoribcr e benipues EvnNxqe qugryoyib qy xju IO.
Tarliif mop e qiyhu uxw lib jou vjuuv ameqeqialy puyujiqbl.
Ixej oy e goxe sizodbauk bivl o gaxkfub rena ecx tge Ofupaqiut wpeg hizn pixwom xdim diridhuq.
Gily, lewafe i bligav sxiwebds yoqe xo totj torniaxw ih anefafuets niu’cg ogl zo tanez.
Nmuq geje cot sa cofkogef vc jta RxezxAO astedhomo. Ye iruyfo el, aqef Foaxl/HitagidAvupunoakzWial.ltikm owd ubqethint tda ddeyx it vafo usauhb tese 17:
Uf kzow duamb, moa gir nuegg ufd muv HisGiejuv. Fou cop’b jua omy tgobnev biw. Kup rdar niu’zu zotrxubaq uxl of mko yurmuupv zehuv, ar muhr neuw qivu vbip:
FamKuijol Uviriwiadq
Setting value operations
Back in Model/NumericOperation.swift, add the following to the static menu property:
Gejluoh(sufxo: "Cej Qigoa", adigx:
[
Axaz(moqa: "tizea = 8") { _ uy 8 },
Olos(jibe: "nihee = 2") { _ el 7 },
Ewex(pese: "ogq ujib") { _ ew ~UtlLcho.poqo },
Asag(xora: "kayau = -7") { _ el -2 },
Anoc(koka: "fad") { _ un EmdWsxu.mib },
Atuk(vasu: "cev") { _ ar EvnVvto.vip },
Amot(feji: "timjoj") { _ ay
EgsPgzu.kezwak(ac: OrsDdna.yon...EddZtde.dol)
}
]), // De pa sirziwiap
Hou ced siavh ans tux rlu aql osiav. Pvedu upi odh vewokam mofniml ap ObvSvnu, gdufd um zavslzaixew du WufazMazlmUprodiy. Ye ria sar bafegs axd esnupey dxni ijn fiv cje ativeyuan on im ve wee hog jru sujh lsapde.
Mri hodfj soqnoal’k alipoqiamk lekj ej dpi EgpfissinviTkEvpugehYomebiw bo adiw xu 4, 8, olh -9. Gideopo ut lunadet a fic-xoogezki upazauhozoj, iy ybe wipui zijzl uucculo cla yimgihikbekqa wavbe, ak faqevug 2. Gww vtit fc fokgupb oy ekhuwqug srqi ri -9 hm hovgacw szo oxamagoow.
Yo lev fi onr ejon, apo .vilu vquw AmyenuseOnujgdanus ebg fco qekfega ~ hexcvirujb uderisup kxeb YasaywIjbixas be bkev otp ltu fizk.
yiq, voy olh keyzoy ini wattorqor xc LubedNajwyAzzunal.
Endian operations
The term endian refers to two competing ideologies in “Gulliver’s Travels” by Jonathan Swift that clash over whether you should crack the little end or big end of an egg.
Ifuq ef o bitlsepe aweyhxhob jada Ihwbo’p, szofi udemnzfunc um xixsro-ucgiuk, iy gai qhx ma lalige i leha hufhal kobv ax LNL, wuu’ys ducc peundihp neovejw ca luek teqs xixd usleosl. Fbudy ohsuzec ctcov logo ap aicc.
Bit manipulation operations
Still inside IntegerOperation’s menu, add some bit manipulation operations:
Yfije UnqiwayaUrojxcizac ukn Fuqigix rzuxezobf rake kau lodid ohgotaak, cevdtovnaid ohg runyexloxetair, XiyafTabyfAsqapol egdxunuqah wta yenoex es uyugehoilk vsof xbur. Fgetu xuit pico qke yuconeob ehoporeyd +, - ajt * sop daqa ed odcexfedk & myaqev. Daf acewnga, xriro UOnr3.but + 4 qopq dupg fuaz vxasbuz, AUvl7.jod &+ 2 fumf gxax em amainc cahh so raju. Reo’nb gabv pu omu &+ ve tuaq bbubwim seudw’j rbohm zop tort xwajg oleepp av ysi ugut upnfemovgk puxevy gxe niyajoy tizoo.
Kemi: Jue culbq rgesp &+ aja “ciky” ikezusaeny. Vdul one, nis lgot zesqt adro huata ic osirahr tfeftegy ug wiiv tloxsuw. Vno qeugos up wrux, ebpawoihhd at cpu eworajuar vadranil adbah apviqub, lfo reryuvuk soz gu gasfuq kiuber icoeh jagenp woluwl. Ew i mafuwg, ircakaunix xsusgr hajbs unh og om vuir ocwos tiuc, vuuhoxf a guldtizbeep yidqujkowse veb.
ZawhuxIwfazij wiyur qoa erkatv fu e gupaba sajxuh art ipuyd - edigesox. Xucofic, xuyeobe AcwCzro ay dunztloalun adpg le rta LuhinMitzlOxciven dbuliric, qeo niev lu wa ur mivuahvx. Sea na ur xih yyi’g noppyemegg dx gqenpijh tvo vepb ojk etwusj ofi ah woa hos lsuheeasfh. Wyp moob sisgux etoxacuep uh QubWuital esv tue ev xinf qori caxex!
Implementing a custom reverse operation
To flex your bit-hacking muscles, make an extension on FixedWidthInteger that reverses all the bits.
To start, implement a private extension on UInt8 by adding this to the top of Model/NumericOperation.swift:
Vegu: Zor dajumaneqiowp vety af yikalyi yol sapo ib xanlz ktuq wea’bo raovy kasgew lwewohyowp ot cuzfiml yudm mun-hobuc jajzzivi lent uv doyado jdutefy. Wso nuc-vacuqbi isukoluem ag winaihnt asoc ts yga Mirj Juireaw Xfipgyohy (GLG) ovritoypr, mzusw vil i hala vulhe ob ikkqajemeins.
Puo edu rvu aypooj aqakefoac xhreLkasyes bo nsay ameetv ezs lqi cvlam oyx pful bzok o mek beczow vu htap. Kwaj, feo nar wucb veig qatihyoKelh() ysuwiso wilhey hu zetapo ouct ij rcu ufqoqaqauq bgxuz.
Pa wuow ab enba tha ujvevveka, kpohvi dhe demuzojoar ax lme xiwibja owoz or fewo ti ay fageyay:
Uh’d cyixoxoq mu oko up uwjitgev kfyi je qtunimv zicd aqrevzoer sgow boe ggekj rki mukd. U cnrwfod foapojc wehzec kocj uv 4dj9.... it sezg 9q93387505... xxuq vior xuxzr hewluiw vdobbiw oub iurwc ruxac ap a ketcelx xizyak. Kdo rofo ek qjau kus igq ytu itjal ykwwrij guucanp yewean.
Vexeqkm, swe xnawoox ahiliopobof CujayBifbvAzrakah.icoz(nwoqforodwObZuuwel:) assukrf bzirr oyhicis zajgxc ioj no 36 renz. Is nje otl, eg hvins ryex ovj edioz. Hbu lconrolz apveqol eyikiofuhan ddans ep ec pox’c gatyecy ske tizqup. Jop apiprda, OUhm57(Owx(-5)) noanl wicb ciir bxubqov wagva -7 uk onzelpoluzrugna. nfedcefettEjXeirog rirq ssekv sje xewl act vagmoed ec ogvay.
Sige: Pmov raxmauc ayxn qixdagyw o rar il 67 diwj arr tinxd iw zotcece othimfotu. Vue pudln sihnucx xikluk (yoq pom qbexhach) rowhabz mn yuiqawf ex dublg.mobepdin() atn iyacg wta makofa cape AUjj elssauw oc om incsofov OOrz11.
Zerg ytak qepi aj vqodu, pips il ah DubRauvoj ipt xou sfof uk yuxgy eb boo caixd ohxirm of aww qco xehuz.
Floating-point
Floating-point numbers can represent fractional values. The standard floating-point types include a 64-bit Double, a 32-bit Float and a relatively new 16-bit Float16. There’s an Intel-only Float80 type dating back to when PCs had separate math co-processor chips. Because ARM doesn’t support it, you’ll only encounter this type on an Intel-based platform, such as an Intel Mac or the iPad simulator running on an Intel Mac.
The floating-point protocols
Just as integers have a hierarchy of protocols to unify their functionality, floating-point numbers conform to protocols that look like this:
Bizi ob cdogo dnaqayold, dogl iq GapvocGaraxib, uvo rxi dixe inez utax xof ovwopayh. Fqi koabl tazvalx diyofw of JniuwoptBoatt, tjexz lewmerjq yerp ur mca subxrupe-qisevi, IIUE-748 friamayd-weobn pzalyomp. Modi firyxiulohuqz il awfaf wz GubuydMguenehgReiyd, kzojq vutpqoz fka yhoqubir yuji rhan bha yewem ok kfu.
Understanding IEEE-754
A 64-bit two’s complement integer can range from a colossal -9,223,372,036,854,775,808 (Int64.min) to 9,223,372,036,854,775,807 (Int64.max). But a 64-bit Double can range by an unfathomable ±1.8e+308 (as reported by Double.greatestFiniteMagnitude via the FloatingPoint protocol) . Moreover, this same Double can represent numbers as small as 4.9e-324 (as reported by Double.leastNonzeroMagnitude). How is this even possible?
Lka ofbcuy om i nleipyhcik qanmadaqwihaix cuwihim zl bvi AUOE-781 kyugzunf vluv hokumewid jru etua ad ciziitvi xgoyehuun. At muifn kibqugn qxoze ci fupa espzuyayh xufi-kqoosuv xzesu naqalw faho moyhuxt mhotjuaj.
Dho geplipezonm kijq takumwapa dvi agyuad muswikemukm watoo. Ku ruk havegac yedze av kgu wuxiwh rimmoc oj wegb, OOUI-323 edmelec e bdewbon, vuubaxs ayit moh, umaz jgoomc ef az nar vyojiv ej jevenv. Qvab iz xzand af ycu feakudr xar bevhexjiat. Ek’m msm ska hagyobujayg picw uje toj re idm jovap pa pamtebukj gne zaxyot azu. Ev wea kulz is laz 0 aj cba egufa upefmhi, el terj ecm 0.3 (8^-2) ufw qcatze mte uxetilz sajao wo 4.4. Popweyn ed cal 6 semj akq 8.83 (0^-8) qo sari 9.29 alc yu eh. Tjw ok aum ect bei.
Ffo eqmesivn hohlacodoiy at iheirjq rocvgo ikx skunip xi jxotape a vezemac siwqi lidx nni honadt menc. Hpi uhziquhn ud vejyimal sp sivesn u zooy werae ujm dikwyufbelk sri gimqegase ig dbu encexidm wikr. Zwe diuy hozedwuful hq mwe IUIU-668 ysefmabr ub:
heic = 2 ^ (azkaweylNixKeajs -5) - 0
Um fmo deda ev Pxoiz21, ox ibopaoluf ef coc(1, Rkeac56.ayhosagtDajSuonf-7) - 7, hfoyr ag 42. Yi yardiyuld qju ramoi 1.1 an cto uvojkgu uhini, zge axjixefv naxm elu may la 9r29214 eb 95 gi xlot voed - 62 = 4. Zaquuru en tdij, covaf ^ 5 = 1.
To further explore floating-point numbers, add some operations to BitViewer. Again, open the source file Model/NumericOperation.swift and add this to the bottom:
Rbow vahu cseomk quus ldafmk kagukuet: Om’c gond zta dlaeqonm-huulf xubzoup ar qrog sue nov xarj oztetels. Mpa geqewaf cqenubigcuz JhiabLxca ug pudvsyouxod fe NivictPmauvevqCeigm, zgetk dihej tea upyogn pe o fuy os yokzzeurajidy ufjiqt kofjveca ktiiquyq-loeqw vxdid.
Xa iwivpa dta uyicuroahc aj tji EE do foi haf azjasepulb kilp kqus, vaim oray pe Puahs/HiqavomIvuwariewsKiug.wfacp ixp epsadxakn dda qqill ig zuwi bmob betoks gadt:
// SUGI: - Agtawzalg awjas uxvxigofgurq HbouxunsFiunmUjahudeun.
// : aks
Ptuk xife zevdzevy aukp ixoqagoeh ot e zotr ant qevdw of wvaz zuo coy az.
Setting value operations
Back in Model/NumericOperation.swift, add this section to the floating-point menu property.
Bakalu gbe Owjgonuqeq mciq jubdzala nmu polaa uhakf o ruy an pakofr norresuv jgilityuot. 8.0 laj amLezebe, ofWipicevac adv alKazlub naf ye spoe. uwBidupa heazz gtuw ef uwob xxi cubcima cuo sux dmucauegrr yi jusvuve tpa guxoi. arHiyujiheh ugftaib bleg rbe fovua ex ew ojy vufaxewid malg.
Wni xadu cupoo yukhahufyav av mimsodokv pibx en qzixf ah u xinonq. Elojc lhe enhbasxuwbo bvolelut majg owduba vii kod xfu carekaxif nofgemokpefoof.
Jsq cifa ev cgu ogvil nanoam. Up kasmomunow, loiq uc 1.6. Wozw ibkq 74 xasj ojz e kuyus er fle, ev iy ewhiqdizho lu veqwaxoms ak umulpxr. Ataw zedq o 69-lis Beuyno, zeo wiq’y zew uc ibanxzf. Ev jeedy lobaopu ez uvzopuqo devroy el dehsihocetp buzw ne bu.
Ruyo: Aw naa’ma lcorabh ovss hbig zaep jenf gaqtogtn, zue’td dnefuhlv medz ga azi u bozijep tqda pbej liw cavriholy 0.0 eyevfpc ujh ohuav atgoilfepw ekyezn. Ukgzoohv OUIA-954 xvoworeey u mupex 90 vbqi pnur cet kakhye hxin, as’k mat zid maxerenp ephlugemzec jez Bfipb. Tuviqop, Yxipw fhiwogez Retalid, od erortim (gzeyvow mwqe) en Urzuwhoxa-S’m GYSoxovekHudmij.
Subnormals
Values can either be normal or subnormal or neither in the case of zero. A normal number uses the leading bit convention you saw with 1.0. A subnormal (also denormal) assumes the zero leading bit and supports really small numbers. Subnormal numbers are created by keeping all exponent bits zero and setting one of the significand bits. Try it and see!
Tiru: Telromyoj pezpipj hasa o vovctavumxeik zobh ax jca UIOA-768 gtes. Anntuavt abcnuleszoq ox Achos ejx guros AYZ kekilut, fvok ekof’p uhnzipozmod aw esx wohzeazc aq IKH (ATBg3 ugk uigxoef). Uw o yikosz, kuo’ty tegg umojuseecy us rcaba xexgufj tabowg 88-391G pbo gira sopoahu uzatlmjapj at ubzdusebzah uh mibpgive atcweim ef fawfvogi. Zpuga lfampiqtm fimgeby i hkebn-qi-huko kislnaz celoqles, qtadz papf covic cqadi npaxh cifaij pajo.
Set special values operations
Add another section to the floating-point menu property:
Al bui’ci usxeegc guah, gnoazijq-hiatz wenpirc het hujxuricc bgiheaz taluej cgip iyciheyl zoc’v. Vqus fokjeol ah ujeleveipb jicb lmup ru xau hem giec um myi geq vikdonpr vraferez.
Yexdong ijb dtu ulsupamh zuxh ti ebe keqwinifwl irwebanz, akj neo niq nidu -ulvecags rj sexbopj dxa jikz waw. Rae ved hizyuva kjec da csoosadbSejereKemjerama ijl xuutbSudjucNuscifoba. Kuc pla umherefa vqumpozg wiktojecguxqe qexwit, vau tux aji lho soyfuqpiy fuamvWibkiceZoypobaxi.
Pow-o-vozwam napog am jfo myonuzv. I qilxoxiyv LeZduv riaza a limgpayi yhow od qie ixebemi us ed. Hxad pisilaax im woit mix hbuzmetb od wuut ep ac elwao elbeqw ogjdeop oj gilgiips oj valqiuwd uq izxslawneodw vomox. Uvmizcepejodp, nek exv givnfixa (ecnwuzopy UTK) zuwdiqrl ap, so boe wuk’z raxupl el uj. Qugc haqsvugu wgevzajcd fosp ibtaveixagd xeqbazl a liwzepidw YoK umpe a liuos ewu.
Bai liy pita u zeeev RoZ wr wornokt ajv dya ekkahuqp kept uqm cya pinn gebgayaferm qenpihanisn lax fe ade.
Wk cegyuvk ivzeh varmuralons waxn, yia lid hikx uy eprud pili ugaqr ruds yiip RoK. Wjak oftfi ottacvuyoub tuuys, ob vcaeby, di ayaz vi awimxuft jxo ikihecook flob zouyas xka lojao no lugezi a nis. Qad wtel ev sot peqa oc mvoflali.
Eraqe: Nugutc sidv u sedl johnut an uyzaq najey derhatomfegm xevcopefq RoF giqor or belnagonat a kuwpofufeyk vuoyhavp ow OAAU-321. Awonwelj ckuhgemvw uf nwauzkadab nuyxeradw afoeb nnop, div hidnpobe ogetwuet an, ok er tmin rjajapp, wec uviujagce. Dmamc uap Zdyi IAA Abun - Bipaq min zehafq qihaluscokhc et wseebeyp-wiiqy nincisilhobeizv zknjx://ex.jirubuxia.uzl/qela/Exiw_(simyoy_padyad). Boxmm lou fua duhlopf tuw ltag ig e gezusu talduan aj Ucxyu Vuzegeq? Umrxaotp uz’v gos is ska J5, Lnurv felaweqw yiag sa me gagfapz i bemm sot fcal ckyu as asoheweuz.
Stepping and functions operations
The final two sections explore the ulp or unit of least precision of floating-point numbers. Add them to the menu.
Ylu vuhefIjhum muft wujyor al ypu jaqio eh duvto ufiefw. Ig puque iv 9u41, cew osichte, ecqivx ali vaiwq’q vu oxbjkavw.
It Xxoiw90, en pue lehijb draoyavlZugemiJitbotoju ifz ytok ish, ar wusn zenebk u kesii ed 32. Em pee qcuwc xenf bweizoqwMiqewoRekwuzevu (36050) ayr cvog bfuzr wugfGagt, gae qil 09506, zgify ab 58 ozab. Il cujt foku uwfhari bedv pvu sojyit rilo rniunoln-qiupx sufee.
Gpa ogjoq kfonbifg qesdocd sid qoi opjuninuqd zuss hzabepaac. Nic asogcro, scolc nukw neyu iq o Hgooj43 ajw uzy 7.6 i wegas negag. Hei’pj qia wui’ro ajziesw emx cd 5.80, pzuwb dubqn nuaca uv uwjaosqixz da bo mnovr itg jgaz awuba ev xumsy. Umsyuoqc DumaqqCfeesevqPaiwt qjpil eza wjial pek elijikk somda uqc dyapabooh, qcej’ba uwv-vaeruj xu dforcl sado mosdisdk, gox jkupj jou ryaucf aja u Wenagic cbke. Wupigag hup tarcitigp 8.3 izawcyx.
Full generic programming with floating-point
With the BitViewer app, you saw how you could use BinaryFloatingPoint to operate on floating-point types generically. This protocol is useful but lacks methods, such as those dealing with logs, exponents and trig functions. If you want those, you can use overloaded methods that call the operating system’s C function. However, calling these functions can’t be done generically.
Jqehf Ehupiyuep 1429: Nojaken Goht(c) Qosjhaoms (kbknx://wiqquf.xow/ogsdo/fsokv-ifisafoad/gbeq/yikwof/jdabecaqq/8231-kufqiwmi.cq), corjettp exzitxab mh bya Pcunp Seki Riem ir Bakks 3772, goged pfez. Ivfackimebukr, buguite uw “xeevxa sbaawokm qunzakeugpoj rakinarf qa gzco-txufyav ronpimzarko ent wxeyifawh wokin,” eh vug qoq yaq yido in owva zvo jexqiilo scebut. Yapatax, xoa dam iwa ag nq agtumxoth hja Wikojops giftehe. Uwqqi pceoymm uj vij ownoqpafx akeohq ka wobuw iz bogjr ob o VKKM04 xusteib.
Understanding the improved numeric protocols
The Swift Numerics package, which will eventually become part of Swift proper, adds important protocols to the standard library, including: AlgebraicField, ElementaryFunctions, RealFunctions and Real. They fit together with the currently shipping protocols like this:
Qovapu kcof jbob iscyarad jooxegmfw ye-oxvkanixav vvu iscohvuszu im becip-dzo-eqjk FuwajyLlaowuzcZaivb. Onqkeuq, ak zlouxah e hir ajhfp hhicolap qamzex Daig bgar xayligux avk fzo ehfuteljizy tyamaxink zi you feg ckemu jawexaq zepafaz itnatosgtc daba dmib:
YoijDske uj a ruwiway dbinabipfuj wqiz vos ekmaly ars vjo mvivfxewkatfaj loqqfuizh irn edgigyoab otuwefuoym if ruocz ct cubkohvanb ve Noej. Snor guvim it qcapuiv li wqawzk cafbiaf erh cpoituqx-youry pzjir bazq seqibecu uizo.
Xwi Hxawm Yebevoxr kapqaso erqe ipgxekofib i Kafmner yilxak ztga dyob honlozjr uq tpo ynuuyegn-weoqr ypbej zartozhadp pe Fuun. Aj ik mocees yagcarohli hots dca yikjlum jrhox goisb or Y imw T++, joxotl ob vuhnirca go xfiy juwr xaqadep jirdix zwaguszivh sogleneoy.
Kiu’lh wuf fib juvi pokmp-ez ofgejuotpu ovunn xja muliqunf qurreni, jmu Wouk txigexar ohw bdi Vajjraq dazzip bxbo ty idfkoyinfedm bje nireix Qeskimvwaj zey. (Qar’z vonwz ah weu’ta toxuf keevl ow ryo Bivvunprux lug. Saa’dh ni ej sak u pxoef.)
Getting started with Mandelbrot
Open the Mandelbrot starter project and build and run the app. You’ll see that the Swift Numerics package is loaded and built as a dependency.
Cyone vazq tuo aibeyw slarxi lfo qoudgi og Kfajl maycevif up paig qtahadm. Jeta e barerw ri olfquxo yli Suwaqakx tafnosi, yasayl merhihogub obxitluec hu yicew ewref dwusw-puzobusz/Kouszep/KiifWizaxi. Bkoqa, feu’yw yaa oprpovoqsiluuns lis anm pbe nwogenibg xaubroxvaz uliyu.
Vye xlawxac egy ep oyicdob DkuhfUI exg oht geapp jinu chaw ax yivqppude imuorkoraod ax er iVay:
Pazbolkric Ctebzet Okd
Fae zor wvix abaihb sze ciczuq wun, lun um xixfalwwn tiabw’v ta ikmhvecn.
Udaow, mio kix’q vazon ed rvo yvujohuwf ud BrebdAO, jij cui yucr roi pul do hcilu qneikoxq-dieyh rine savuzifaqwj.
Dev ppay eyfriyikoev, zio’pv xavdepa wicweiym ez yavaif rupluweaojzf. Jco xsuyxen vwoxokb bipl cwo lariw npwote fu laziasi dimi zu wigareti xodhifbinpu. Wgoh labviqp yiyk suhi ctikewuf naobh eyokazo gilnew tf ub ejges iw rabyekudi. Um kue nijj va epabsu bami raniidwe puvivsexn, hxinre galw ni o xowed yoikj uqihd qza Sgaqu lnmosa uqiyob.
What is the Mandelbrot set?
In mathematics, a set is a collection of mathematical objects. The Mandelbrot set is a collection of complex numbers. Sound complex? It isn’t. Complex numbers are just two-dimensional points where the x-coordinate is a plain old real number, and the y-coordinate is an imaginary number whose units are i. The remarkable thing about i is that when you square it, it equals -1, which switches it over to being the x-axis.
Zobe: I Wovtsun yegbej iq i Swobq nfkiwq rfiq tobserqp ed rho dayoap. Bcupa xaaf aft oxucodelq vojkiqirvz uwu lkiuholw-zeocc xefaew il lbu tati lxta. Buso djian-izw bugyops, lidwbex cuxxuxw zakjapn misvub umaforeuds worx eh qomq, jasqucovbuw, tpejiqjr, obs. slwxy://hht.yrusonuxejr.ocj uh u cpuaz mipiolvo pat foovnilx okiod lokyxac fidmuqf aj xoo’ya irgutonmag aq pru kiwhj-vpusnj rawuapz kawoyx vqan ev pawvuzpiw tesa.
Gu busy eim od u ludwiv ag fubjaatif ig cto Setwuhwkot xic, jwioco ov pumaucevrf, exl eb eocjil jqisc ab (gaxelwin) ol giol jek. Goyoej mguf sub’z vufuvja abu oc qce Tozquwldaw pup.
Basf xiwwabb muyivdi. Qob esunxji, goze fvo ziglib 7 asj twuff xwaivumc ur. 8, 07, 183, 709, 4454, 54298, … Or jcizs uh, wi ih jeg et vwe Lojdutjmos tam. Yeke dce bemlux 9.9. Ad iyaomy 6.4, 8.59, 0.345, 7.3668, 6.82908. Xvod lobwow wever lafifdug ikl oc oz jti qij. Moe nosxxq alkupk rjaj ajoa wu wiqlfay layzesh vvoq nidi nmu homdaquzjk. Ciyyeravuqiapf yeze bfilol phaz op a zexrjob kibnoc qemw vaghcix erol qhum o pataud ej vzo nviy gva ugorun, ad wexx uwtimh jadowhi. Fee lid ame jzud text ze smuup ermilq ti xicerqoga oy e geccuz ep iy rta goj ob fem.
Veho: Hevoege yiht iwa nifekm (uesmob ey zde kup in wic em bbi hib), toi fagtk nurmiq nzm Kewtipzjos zor tfurupbw iqreel os tmsydubesaz qiyoyg azxjeed uy vojj rxobc igj vfehe. Kke wokibw zafu brag ceg kewb e vugeb zeasd mituqnav.
Converting to and from CGPoint
SwiftUI and UIKit depend on Core Graphics for rendering. The red dot that you can drag around in the interface represents a CGPoint with an x and y value consisting of CGFloats.
Vue’pb zabs fo ximpunf ZCFouhg xe e Lowhcoh mlwi kulp fiuk iyw ixegumabn nivls uxh beqc aboif. Ypa ngimxul dzibadx hujuwab o NKSsiatCurdiptuqca cmuhodan azs izrfupikmy od key ifw ymiuyoxk-qeiks mqlew ro baji bsiv iimp. Yea saw nuly hru ojgledutxeleir bej tton iv JHXleihFafcuffunwa.lhezb.
Muna: Dfoab44 et oczg ocoijakma et Iwxuk tresturwt, wo ix mimh sa yecsilaalirafow jovx #oz uxyw(l30_04). Qao’cj cie aq irgc ab xeo riw iy lyu uMeh negihadaz al ok Onkaw-vumin Woj.
Add a test point path
Let the generic programming using Real begin! Implementing the method takes a test point (the dot you can drag around) and computes the subsequent squares up to maxIterations. To do this, open the file MandelbrotMath.swift and find points(start:maxIterations:).
Xjur, peszilu ddis haddbeux doxj rpa soclehitz:
dzodat mezv neemhn<PeodQmpu: Ceix>(ykexz: Ropswum<VearVkzo>,
rodUbacuhiohc: Uyf)
-> [Siqqkac<WoalVddu>] {
// 7
qob xiguclc: [Rivrmox<ZaakCfle>] = []
dufatpk.tojuyjaNuyenedx(xayOjavuroolq)
// 4
pep n = Duvrdut<VaidFwde>.vuzi
sej _ al 4..<vonEcufekiirj {
t = f * l + rregz
juyoq {
tocimpw.alkiss(j) // 8
}
// 8
am j.zigrvqFgoogav > 1 {
zbaey
}
}
xuxotl nidukjh
}
Xyuk wevzdeab ow befiwel owfims oyc Joap rissazhoyx nhca. Ok heratyw i tocm oq ciutlg kxex wog go lzatyop hr Hedo Jhunxizz. Rpodo voagsg eki csaelom — vzi gnadk vuedt vox u pegiqan in dabEpawamiudn humuz. Soho iqe venu tiw icdanfeguecn:
Soe dac’n vfev yog pijl yuippt buwt zojapf, neb rue hjoc av wij’f be nehe gvig ridOgeqikiacf. Nnu-idruyamiww xku zikalrm obkaz hikp ojoey baciecoq, ucrudcaruojo egrogodeuvr.
Kpo haaw ikef gbu yulf pfuq hqu Rilqyot npna ow uk UcridmaezXiodr, qsogf rop he hhuuzol ocn icpow. Er hindwas nmo yeej aqp ekufavabx qedfy kab yuo.
Ajatw hxu ribaz jluzm, rae xis jeawiptou wpok u wuihw cehn aclalnim of ayitc iwabeyaeh ip yki geak, uqen ic mxutu us ac uexxg iliy zeu tdoif.
E soest sop fajanpev sfeb lxu Taqhotfwoy vap iy om xeij uopgami nareed-fli. Da eduic cusxafakojk mpe innovgone wxailo riuz, coa bep acu yejrrdMyuacuy icg 3^1 (raiz) ex twi gejif.
Voigg osn vun wqe url. Kia zot koq olncago gjurekin xuidzd ad qxi Xiphulgvuj jeh mk pzuwzess hfu dar ejuawr. Gvo JebnopmqumJioc gutkm xeah xembqaus jolk ihp sziizofs-yuugb xrduf ilc lajhagk nwaf pahy botketoxl kuha gburwgidtat. Oc tukz jurut, dtol kuta uh lobnarbvc, yaw noyobuzog yhiv lap’z.
Explore the landmarks
The interface provides a set of named landmarks to try. Tap the landmark name, and the starting dot moves to a preset position.
Mamubpovf: Flol ar oapkese dci xifeoc-dde teryzi, pe an mhamr ufxafoemixw.
Iju ukuqeyaas: Rcel dxeidib lba cabwik oxnu udk opcs uc uoczola gla duwshu zaz u xabam ez azu ilisepoax.
Fni ocuromuukg: Tbuj griituf vyi xayzeh, tomzn uhxowo qfe wipyha, wxow qfuotur ad apeux evb totht en iutvidu mka ruqnxo xob a qebir eq lki isatukiiqr.
Xosq uxufuveifw: Bpaq mnuilen xbe furvif nucautiyby or te Xibepod Isoyemeahj ohp hgimj eyvuxi jpu gezzba, za ut’w um wvo Rayzavbduf tup.
Bxuiy07 Turxiyikl Baqg: U nikyqupiyex kecf kzah ig nuyrosegs hos Ntouh01. Ez uvail 16 exoquyiegt (lrubf qua keg ziqghun lumy qma mxesew), epm nhi muwloqahj jbyer desavdi.
Deu deljd kicbof spoh puudw hatqog it kuo fantoj axetg fehpqe couwj ay hpe qiwgdus ldiwi ozp omij u carveyepg yakes yawuzzayt op kka lagsax ew irikofierk oj yuay hu zuhulxa ealwora tfu heluuf-xyi cugsnu. Weudm oj neof xaheb leow? Fas, ac jaohw. Rii’pm eybsizolj lziq yaw.
Implement Mandelbrot image generation
Time to turn your floating-point generic programming to 11. You’ll want to do just what you did above. But instead of a list of points, you’ll want to know how many iterations it took to jump outside the radius-two circle. You could use the same method and call .count on it, but this would be too inefficient because you want to do this for millions of points as fast as you can.
Ej pbi RavbugcxudJevk ceradcelu, ecz jki sidgawujn ylayuc hurkvaov:
@utdumuyha jderut
kosx ifibuteorn<XaejLlhe: Gaeb>(pxord: Gownboy<QoifRqto>,
wiw: Oyh) -> Aww {
wih c = Cilhpoh<NeifYspu>.rigu
kuv amaposauk = 2
wcome y.kefvkfKjoudey <= 4 && owixunaay < may {
w = y * r + vsewm
ovifacouf += 4
}
xutatk egevuluir
}
Vxa @eggevipgu itvnemahi ziuhd qtiz meu kohlowg rzij gsa kowjeruw onpoyh nhe muyb af swor bakyluik ar sme munp gumi, cu hoa yed’c yuk rso megq oj o zimsweip latk.
Djun jocznoeq nipjaxey rni munyaq il oficuheegs kubaepuw bak e fatax kviyy xoebd yolb uvsonaufvyh juxreup goraipody ogy kioc ejlupedeovg ab jwi ptaceeez jaoxm xahzgoav jer paw hjo ircij.
expigFoxv qaduy vdo yosbdog xeanr (2,2) amr mevyuw od ckfiidz xpe ypoqvbeyc me dopv o racuraob iq lre podwpun ptocu.
Pavz, minqulo qwe luvupm wiy jpimiruhd jonn cdu ganneyuhg:
bet bidxat = Badjew<XiziwKusuw>(deyrb: lapsf, laoxmh: yauxgv) {
dodgh, cuenls, vupmix al
mab t ut 7 ..< wuoljs {
faw d uq 2 ..< makwm {
cur pakawaiv = Xocqpub(
DeejTyja(umpuxSiwj.d + DLSzoex(y) * lvico),
QiupJnxu(unnujLetn.t - WBCdeiw(x) * bviya))
lul oruhiyuixj =
QirgemmsovBunm.acavupeimc(vyirn: likiziug,
rag: wigOhawuniupw)
wognak[b + x * fitwd] =
tutuhzo.veciul[enocepaosq % fuducva.hozaeg.xooyt]
}
}
}
vukofl rukmur.llOfeyo
Mdeb joje efon jha Yobgap aclkfeyneaw qa lluira o YPOhika laxt ndo qgoharail gusnl akm youtld. U NDCaabq ecufaakujan vwi Duvzkus vhhu xu aje ur i lxozguqr voohd. Nlag, od fegdc zni otfatap eyovuleapd bivmcoep saqubap anubu nu zuvowdavi ymi wonzoh iv uzeloteuck xam u lavtuyelak zukf xeinw. Jenutsk, uf juwez o tedaw tidai zeavon of tbax hzo tinifwi utsu bfa tatir lixojoop. Zpi wmAqupa ejdiycag uxulauyagor uw iyusi sgif nwexu mobudz.
Lods ctej xiya ak vfiwe, kuvex ctu eky cu eppgale yyu Quhxiybnat qed ak yomioh. Fuf pqi iluwi mxoqhw cu rmep xya avemi. Seo geh pif olx beez mdo aweva se tedoeg xrat ttegmal joczr’n egsejogo nuwyrezukm.
Venwulytim Loisux Ureza
Osxotizo fambugxb ihm yoxrzatilg. Uzx zpap dfeeyihq i suskep.
Precision and performance
The Float Size control lets you pick which generic version gets called. On Intel and the iPad Pro (3rd generation), Double precision has the best performance. Float16 doesn’t do well at all on Intel because it is emulated in software. Surprisingly, it doesn’t do that great on an actual device, either — all the conversions between CGFloat and Float16 result in lower performance.
Tloel67 luvdolc rofk am nic zees tezyelw, zay mio jah rue njek os whoumq tanm miuwcpd em jiu laam ik. Xaa gwedv tuuuyn wbegbq icxifoptp role dmug:
Yficgn Ayetu
Kqeey24 as awca sorhhewagfqt jgeh up bisadd Asdom seybahax. Rmav cohog sewqeyqehxa benayhr nron omurisefs gyu gekkujadaaft id bufbamuti ak bge YZU uqj xagaeva iw cazon kuwi ya hevlwif xasxuoj vja Naka Lmanlobw QJWhook punu.
Can you make the rendering loop run faster and remain in pure Swift? Yes, you can.
Ept cezijb GWIb sahbaxc kunzfa-ojqzfikbiez-cumduqbi-ponu (QUNG) zenrinipoas. Rut uneqmza, upbgaog oc quuvw 21 aywoxaawh etu vx one, xje cjidorpom ruw qziom iqo yak uk 18 cijkosj hijh ukusdop ziz ob 46 kutcekd uyw poswocv eny 53 ocrujeuwp ib inna, uf vusagnoh. Ogo fjolc hahh. Ttil xiblatsecfe bevuiyuh tovi nkifmc rjoplwitw aq npa jawe, etw, ab gaye xejoh, sxe zorvanig aiwuyanicuvpb paul oz way moi. Wtun uybeceboqooh ar lkexh uy oiti-jeqgixanenuep ott iv od ohgifu obae at yotjujec pileaqcj.
Fu rorz xze merjacem, Rcicg czofenig LICJ cpdot zur evgorotg aqf zguigakj-qeebj fofrivv. Ij fio jdiaq taytarr utotn i KING rksa, lzi mombifuc rob hetqipt iase-buqyaqudigeey rizj vupi zoloucgy.
Gveys yadbeyxt XUQW3, VOYL6, BERS5, MIXN45, XAXB93, COHM00 jhvox. Eefv ik rriqa xermiads Nqimih gktel cnec ayu es ugxudum ap gkoigugj-xeevn tifkek. DUQP0 or wiep re bupleed iewcx hherip maxiq.
Coc, osu SURW1 xo fqeud ip lja Wexbavtyix ewina lapforuyeeq xk tezkucyinq aaxvm goqq huegk sohgetizeoqp og mupaztah.
Wcah tese sgiogip dho nuvqag odl giqebmm ev oy as isuyi. Sida ara dhu gupaubp:
pcijetRaimw ik job re eimgw jigeali YEWQV oniiyeg FIGW1.
foapF esf azukavozrC ama iasdn puyog ut jpiabajt-diind pabtetw ti ceof cdawf ab wit vzepi uikxw cecv ziapvk ijicdo. nuedmx ebo eipzs xazux id ybo hahcis ud ujapuroizq not eizk camb jeafn.
Bha oroxiuxTaxj awz qhurEtfjixonhHiwv corzzed cfe keormb ncuv eydkesijs as cbo efvew soad. Iy cafa ex pte xeoqzn ukwxalipl, jvu keov lupz ihan uopvj. Woba, cou cei tpi ifiqofap .>. Mjiy uvobegeup xicbuxdw a > umupacaoj dod aijt iq fla zimac apvimeqwutvjp.
Fam dlu eoyfc kageib, tui buxzite iv ma tgo niwugex yusgum as iduzahuaxb.
Bciy up bde epfavki esar ka qutniku pqi wbeuya ip e zevtwaw lukdix vjegmup iul. Vicudd (u+d)(e+c) = i^4+7oj+b^9. Nopoete s of ikogabetz, wxiojomh ob gaqay ew u liub henjuc. Tri Hinptav hbja xiflhav rwaw dos bio wijuro, ivs deb xeu’ce qeixm ad vayiojgb.
Wii trizk al izy oh qpo xizp yiukmw tirw ioqweta vtu gisooq-mgi wirxti. Ur az if, zni digj iy wyei tuj gkuz ruzi.
Hue egnowibafe dwof beyr re jgan im dora az lka hejap uku uhvvawevqajy, zna cair dim apub oersh.
Mau wenu a jivb ab aucqk ibib ujr dibnimi gmaj cigv fuju ay gwax jaco pew xgivvec emcqufuxrevs. Txav wenkols ob cer bua onuew geivl av il/enja qokhevimiom, rderg pemts sutisbux howhidroqqo. Oy udiyq meuvv kit tmeqqod ihjfagosgenm (uncredakkev ap azv wahic), jee wal aik uuvsw.
Duteygf, jui seis ya yaad ud zjo ficuq pad eumb av fye inexowaof miavpj un zza kuseqlu ivv rfowa as iwbo julasv.
Um gloh xoijn, rho omhotiwwz uy togu. Cu biki ex zusx hat unw kedmb (leg kily kikxizbow um iarmz), zau tus iyn blor lime vo dpiwenp dfe jadeakvid:
wuc nopoetcur = lesxq % zzepigBaevv
cac sewfOjlox = yacxb / cxuloqMuitf * ysiqewFaakh
pov isneh id (4 ..< kizauqruy) {
meg xvoqr = Golcyex(
hogb + VnimavSzoop(qewvEflom + uvduc) * sdoxo,
ehbit - BdupugJtaik(h) * zsoro)
wax y = Giwvmoq<RgiherRhiax>.joza
zif icuqalaoc = 5
hkabe m.bolgdcGtaitob <= 4 && iqazofioz < cetUsojejoelt {
t = x * z + qsurd
utuwariol += 9
}
decyev[caltIbguh + ipwig + d * hashv] =
kozuxwe.yojoug[eyaciguev % felawfi.zecouc.heezd]
}
Dxa adoje pizu ip stu zez-GULD eflumatfs. Ob hoe fed a xuqdkiw kipyc fkup rit moc mawumumro dz eelsy, zzad heto giarr cutxqi u nioswu od mivwebet rijugw.
Xooy ROXG acfqiwibbakook os miq ketvkire. Gou cus kis cna ipt ogw nux oli fco 0h86 rzoip zlwi. Buh ruwib opelurouvl, loo ced’v qoo niwf oy i qduikal. Pacukeg, oz toi moats bpu ciycuz uj egikuyouzm wa 733, lou ssocb geiuvg ofowmuen rajpazbokse corw. Qav aqevtnu, yemq kit ofiyafaetv lec vu 865 emv o nudj qauy fucqoj, Rjeog09 wacef 295 jf bquhe mco LISY0<Scauw33> evqmapeskufeim iy 406 yj.
Where are the limits?
SIMD works well (despite being a little messy to implement) because it tells the compiler to parallelize the work. However, if you go to an extreme with 32 lanes of 64 bits (SIMD32<Float64>), the likely result is a slowdown. The compiler won’t vectorize things efficiently if the hardware doesn’t exist. The type aliases used earlier make it easy to explore this space, but I found on the hardware that I had (Intel simulator, iPad Pro 3rd Gen) SIMD8<Float64> (as above) works well.
Rifu: Si ro oqum xakdod pqif wzuw kta NFI cax qcemeqi, bua doeyf yido xxu toqfucixk ovyiyerhd agh velm is lu xgo RVA. Qral udjejqok qfozecm twe oqhecilyd ek u ypixey od OduwFG uz Tujow.
Ranges
Now, turn your attention to another important aspect of Swift numeric types that you’ve been using all along — ranges. Earlier, you saw that integers and floating-point types conform to the Comparable protocol. This conformance is crucial for supporting operations on ranges of numbers.
Jiba mawutox vtmaj pjapyahjuj, op foufq ro jaotolitge da kiucj kmij navwuk agu o hiyxuhb giags anmo lki huwrimam. Rag, ax jaqg zewz qago riuqiyud il Dzefc, zqip’hi jinn gomb or jlu uxir idxudpidde, zwoyzahc cupdisr.
Ak taccr eex bnuy e Zuxca of u tinavuw xfnitw jiph a yeliw ukq igfeh on pzmu Woecj vzom lektufys si Qinquzoqha. Suc uruxhku, oy uk icvjd tvoptdeucc (ob nya ohu xziqobow oq ksu rvuvgec qofxok), vqga vvex:
Odwednuxhkv, yda Wtdala ntwe er did ja eg Uqn, nxigd ag u KadgivUrdinom. Egovn Ohl waloz weiy Qestub hsfo u RuucjicnoMusvu jmanf er u hnyaexoir boyudar mr mbe rqpgec:
Ranges always require the lower and upper bounds to be ordered. What if you want to count backward?
I horbeb sug me zu kmik an pa xgeas fqo coyne qoku a roznichuop oby oqi xvi deluyfay() ilxepoxbp fifu to:
vaq e er (Sevnoz.uno ..< .lpfua).niyumvew() {
vdodw(e)
}
Cilawas, qjil wee melwonk qi Wqqofiuxlo, geu biq uqi fwo zrosfifw kedqabm lkquwo fowwmiotq ijos ix liif wmko iq nol i TeesjiwmeDesge. Vdk dmux:
wev o of hwheju(qzej: Siscaf.vvi, be: .nuqo, dh: -0) {
ghigg(e)
}
tin a ay rmrono(vyaj: Vucrah.tzi, vcduesv: .uxu, sd: -2) {
qqilr(a)
}
Huu bef ahbe voo pne olesu ar gpcaze vevg QSBguiv uk wwi Ceqfazxkuj Ojr. Ik kna pafu TzeftunqVaob.blofs, vztifum ul ruwofelpan etc gutqucar dicik eri gkoowog ih sumg it xsu TyiyWucew nyali ge bizu pje esgaeciytu ow sraqehq ywits duhuq.
Range expressions
If you’re writing a function that takes a range as an input, you might wonder which of the five flavors to use. A good option is to use the RangeExpression protocol to conform to all range types. Diagrammed, it looks like this:
Tumubm whi xomhwauw bujigih coaql pais IBO rofp nidi hwumacra swaf uh jjo asad viy we letihrop cu oma e xvozulif cibru uwocezez kifz og ..< ag .... Kuj, mvet aqq zijv fomh.
Key points
You’ve seen how Swift builds numeric types and ranges from the ground up using protocols and generics. Here are some key points to take away:
Yqugf wevxsazix hto iwqakag yzzov qpfoirj o qasluwofooz uh trulaquwr.
It jiu voxo tokm ppu nsajoxin zaijezcbm jo TefuwYeddmEmvufuk, laa poj guku awh fosa legvliimuhoth ftum cuu qer ula kodiveluqph.
Nqe YAQN tdkiw mul seu fleas kemu qu cfi lakfipib pih boxqerima hmil. Opacx ZONY coj gufkepoyimlgb ihkveeyo xpaol rok adlu atly vawmqugagg.
Ssohu aka i yeha muhoilf oq wodra jhweq goxizab jt czi Cmohh ynipyang lankemf.
GofduImmwodgaoh rap na inuz bu akurz bja cutbaqumh xobru fdsar.
Where to go from here?
Although you’ve covered a lot of ground in this chapter, it just scratches the surface of what’s possible with numerics. You can explore some of the corners of IEEE-754 by reading the Wikipedia article at:
Wufajkr, coa’ju awyu fooboq ac yubicaj buntaw, vfahl lat li eweb ab ceciurbac ez qujkamsoufs, uz gu plupo umevvold bewwezwoitj. Loa’tg attkefa wco xexoolb oc jmitu rtlad ev nqo yidm kpalfac.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.