# On picking an orthogonal vector (and combing coconuts)

Consider the following problem:

Given a non-zero vector

vin 3D space, find a non-zero vectorworthogonal tov(i.e.such thatv.w= 0).

At first sight, this seems easy. For every possible **v** there are an infinite number of orthogonal vectors lying in a plane:

We just need to pick one. But it’s not as trivial as it may seem.

## First attempts

The following vector satisfies **v.w1** = 0:

Unfortunately that **w1** vector can be zero, for instance when **v** = [0 0 1]. The original problem requires a non-zero vector.

Let’s try another one:

Again, it works most of the time, except in some cases, for instance **v** = [1 0 0].

How about adding them together? Certainly **w1** and **w2** cannot be both zero at the same time!

Alas, this still doesn’t work all the time: it fails with **v** = ![1 0 1].

Should we try harder? Isn’t there a linear combination of these that will work all the time?

Well, no. There isn’t.

## You can’t comb a coconut

Sadly, the hairy ball theorem, a consequence of Brouwer’s fixed-point theorem, states that any continuous function *f* that maps the set of unit vectors to orthogonal vectors takes the value zero somewhere.

Whichever way you look at the sphere of unit vectors, a continuous tangent field will always have a zero point:

Most of the maths operations we usually do (adding, multiplying, taking square roots, etc.) are continuous. Fortunately, we are not limited to them: we can use a simple `if()`

construct to create a discontinuity that will save us.

## A very good implementation

Here is my personal implementation of the orthogonal vector problem. **It is very good. It has excellent numerical stability. It only does one test. It is short. It is beautiful. I really hope you consider using it.**

/* Always works if the input is non-zero. * Doesn’t require the input to be normalised. * Doesn’t normalise the output. */ vec3 orthogonal(vec3 v) { return abs(v.x) > abs(v.z) ? vec3(-v.y, v.x, 0.0) : vec3(0.0, -v.z, v.y); }

Many implementations, such as Ogre3D’s, have additional tests or operations to perform this task, and use epsilons and normalised vectors to avoid singularities.

But our only test is actually enough: if |x|>|z|, it means the largest component in absolute value in **v** is either x or y. So we build a vector using x and y. Otherwise, the largest component in absolute value is either y or z. So we build a vector using y and z. That way, we ensure that the length of our returned vector never, ever comes near zero.

Whether some given code will cause inefficient branching is often unclear. In our case, it is very likely that the ternary operator will actually be branchless, with some help of the compiler and the hardware.

That said, how about we try to get rid of the ternary operator, just for fun?

## Going branchless for fun

Let’s see. We had these two candidate vectors, **w1** and **w2**, which worked almost always except when specific values of **v** caused them to be zero. And whatever the constant *k* we may pick, a vector of the form **w1** + *k* **w2** will eventually take the value zero for some value of **v**, too, because of the hairy ball theorem.

Now here comes the trick. Instead of using a constant *k*, we use a function *f(x,y,z)*. This is what our **w** vector looks like:

From now I shall assume that **v** is a unit vector.

What can cause **w** to be zero, then?

One necessary condition is *y = 0*. When *y ≠ 0* we can chose anything we want for *f(x,y,z)*, it’ll always give us a good orthogonal vector. This restricts the problem to the *y = 0* circle, giving us the useful equality *x² + z² = 1*.

The other condition is *x = z*f(x,y,z)*. So if we manage to build a function *f* such that *f(x,y,z)* never equals *x/z*, we win.

Using *x² + z² = 1* we can plot all the possible values for *x/z* as a function of *x*. It will show us, for a given *x*, the values that *f* **cannot** take:

The almost vertical slopes you see go to infinity upwards and downwards. As expected, this prevents us from using a continuous function: it would obviously cross one of these walls at some point.

Well, let’s try a non-continuous function, then. What are our options?

*fmod**floor*,*ceil*,*round*…*fract*

Here is one that I came up with and which works reasonably well:

Look how it nicely avoids *x/z*:

And finally, our resulting branchless code:

/* Requires the input to be normalised. * Doesn’t normalise the output. */ vec3 orthogonal(vec3 v) { float k = fract(abs(v.x) + 0.5); return vec3(-v.y, v.x - k * v.z, k * v.y); }

I find it highly unlikely that this second version will perform better than the branching one. However, I haven’t put much thought into it and maybe someone will come up with a much better solution using the ideas presented here. Have fun!

### Attachments (4)

- math-vector-ortho.png (14.3 KB) - added by 5 years ago.
- math-hairy-ball.png (23.8 KB) - added by 5 years ago.
- plot-1.png (12.8 KB) - added by 5 years ago.
- plot-2.png (15.8 KB) - added by 5 years ago.

Download all attachments as: .zip

## Comments

That seems pretty efficient. What I used to do was much more involved:

which is slower due to two tests.

About your version: you can easily take out the branch by simply computing both vectors and blending. In x86 SSE this would look like:

PS: I used the branchless selection a lot when programming the Cell's SPU. That thing would execute code at such an insane ridiculous speed as long as you avoid branching and used SoA. In the CPU's case, you would use the spu_sel() intrinsic.

What about the correctness of this function?

@anonymous This function will work, but it requires you to provide a vector

`v`

that is not collinear with`u`

. Which brings you back to square one: given`u`

, how do you pick`v`

?This is interesting, thanks.

I've thought about this lately and wouldn't it work to do this?

cross(v, v.zxy * (-1,1,-1))

It's so simple there has to be something wrong with it, but I can't think of any case that would make it fail.

@Bas: Yes, there is necessarily something wrong, since the fixed-point theorem applies to this function. In this case, a simple counterexample is`v = [1 1 -1]`

.The prospect that two randomly picked vectors are orthogonal to each other is precisely zero for any sensible probability distribution on a vector space. So it sounds like you're disappeared some relevant situation here.http://www.aoneassignments.com

Play sonic games free online from this webpage http://sonicgames.xyz and play online sonic games. For play these sonic games there are no need to download anything.

As per my sight the Orthogonal vector is a vector uprooted by 90° regarding a given vector !!!!!! their convergence makes a point of 90°. Assignment Writing Service

You have posted a great tutorial which i like it a lot. I must say students should read this article so that they can learn from it. Purchase grass mats from http://www.grassmatsuk.com

Very good information about the On picking an orthogonal vector which practically makes it work. I am very happy to see this post. Thanks. To get gym mats Click here http://www.rubbergymmats.co.uk/

https://www.dissertationwriting.uk/ I’m really impressed with your article, such great & usefull knowledge you mentioned here

https://lawassignmentshelp.com/ I am so happy to read this. This is the kind of manual that needs to be given and not the random misinformation that's at the other blogs.

It is interesting how you combine the maths with coconuts! Pretty good stuff, we like it. www.derbydrivewaypros.co.uk

Dissertation Guidance Provides Quality Online Dissertation Help For Students. http://www.autocadhelp.net/

This A Good Way To Appreciate The Teacher As They Put Their Efforts To Train Students. UK Dissertation Writers Appreciates The Teachers. http://casegurus.com/

A great example of how a competent post should be made, thanks, others should learn from your blog http://19216811-admin.com/ 192.168.1.1

Windows 10 turns on Bluetooth on your computer system or tool as well as starts looking for tools it could link to. When you see your Bluetooth mouse in the checklist of devices, tap on it. For how to take screen shot in windows 10 go to https://windowsclassroom.com/how-to-take-screenshot-on-windows-8/

Informative post. There are very practical points shared in this post. These points are very helpful in out practical life. Thanks for it. Carry on it. To get heavy duty shelving Click here http://ukheavydutyshelving.uk/

What a great informative post. I like it and appreciate your writing skills. You have done good job. Keep it up.Get online epdm rubber roofing click this http://epdmrubberroofinguk.co.uk/

This article does talk about lot of things in physics which we can see in our academic classrooms teaching. This information can help me to gain more knowledge on this topic. I generally read rush my paper writing service blog tutorials and use them as my examination time reference one as additional material.

Panda Express is a private subsidiary food service industry that has Chinese cuisine as the genre. http://pandaexpress.surveyh.info/ was founded in the year 1983 about 34 years ago at Glendale California United States.

Most of us have probably, at some point, written code resembling this:

Perform velocity damping velocity -= velocity * 0.01f; … or probably the more correct:Per-second damping coefficient float const D = 10.0f;Damp velocity according to timestep velocity -= velocity * D * delta_time;Per-second damping coefficient float const D = 10.0f;Damp velocity (framerate-independent) velocity *= pow(1.f - D / 60.f, 60.f * delta_time);Per-second damping coefficient float const D = 10.0f;Exponentiation base for velocity damping float const D2 = pow(1.f - D / 60.f, 60.f);Damp velocity (framerate-independent) velocity *= pow(D2, delta_time); /* Build a unit quaternion representing the rotationquat quat::fromtwovectors(vec3 u, vec3 v) {

cheap essay writing service uk

https://aroundandroid.com/ps3-emulator-for-android/

Science Channel’s are giving a complete knowledge to its viewers about every thing students write done dissertation on this subjects and show its importance. https://paymetodoyourhomework.xyz

I loved the way you discuss the topic great work thanks for the share Your informative post. https://pythonassignments.xyz

I’m really impressed with your article, such great & usefull knowledge you mentioned here https://www.sociologyassignments.com

I was surfing net and fortunately came across this site and found very interesting stuff here. Its really fun to read. I enjoyed a lot. Thanks for sharing this wonderful information. Food

Thanx For Sharing Such Useful Post Keep It Up :) Assignment Help Online

I’m Really Impressed With Your Article, Such Great & Usefull Knowledge You Mentioned Here Case Study Writing Services

It's nice that you create such good quality posts for us. See this webiste: guida di cracovi

Pick an arbitrary vector that is not collinear with the given vector. For "something rigid", you can have a fixed rule.

help with essay writing - uk essay writing

Nice

NIce post <a href="http://www.facebook.com/waleedrajpoot61">Must see</a>

[url=http://www.facebook.com/waleedrajpoot61]Must[/url]

https://mailto.space/

Mail to my space Pick an arbitrary vector that is not collinear with the given vector. For "something rigid", you can have a fixed rule.

Wow, Really great article i enjoy it very much here I appreciating your knowledge keep sharing kindly check it out pokemon go tutuapp

Thanks for the valuable information, I enjoy reading your blog and always looking for useful articles and news https://192168ll.mobi/ 192.168.1.1

This was really an interesting topic and I kinda agree with what you have mentioned here! <a href='https://pkws.net/'>KFZ</a>

This was really an interesting topic and I kinda agree with what you have mentioned here! KFZ https://pkws.net/

Allassignmenthelp is one of the finest websites I have stumbled upon. It is not only well developed, but has good content as well. It could prove to be an inspiration for many students for their assignments. Assignment Help Online is into assignment writing service sector and helps pupils in completing their academic tasks. https://www.allassignmenthelp.com/

A superior all assignment Help reviews offered by this website with the advantage of online support with high proficiency level based on its latest research and information by professional reviews writers. Wide ranges of subjects are covered with separate writers for each subject. http://bestwritersreviews.com/myassignmenthelp-com-reviews

I recently found many useful information in your website especially this blog page. Among the lots of comments on your articles. Thanks for sharing. lessons online https://acim.biz/

i am for the first time here. I found this board and I in finding It truly helpful & it helped me out a lot. I hope to present something back and help others such as you helped me. non duality teachers http://www.nonduality.xyz/

Which is headquartered in Atlanta Store Support Center, Cobb Country, Georgia, United States and the Home Depot is the largest retailer in the United States. http://customersurvey.xyz/homedepot-survey/

Thank you very much for writing such an interesting article on this topic. This has really made me think and I hope to read more. http://www.cinderconeclaycenter.com http://www.cinderconeclaycenter.com

App Cloner is an application that will allow you to make exact copies of any app on your smartphone or tablet. https://appcloner.xyz/

I have read a few of the articles on your website now, and I really like your style of blogging. I added it to my favorites blog site list and will be checking back soon. Please check out my site as well and let me know what you think. suzuki coin https://suzukicoin.net/

Wow what a Great Information about World Day its exceptionally pleasant educational post. a debt of gratitude is in order for the post. https://www.affordable-dissertation.co.uk/dissertation-writing-services-uk/

Scholars who find it difficult to manage their assessments on orthogonal vector don't worry. Expertsminds provide them assistance and assignment help services. Get your perfect assignment solutions today as our experts and professionals serve the best assignment help services and homework help services to all the students who find it difficult to manage their assignments by own. http://www.expertsminds.com

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post. Cranberry

Mmm.. good to be here in your article or post, whatever, I think I should also work hard for my own website like I see some good and updated working in your site. Cranberry Juice

Much thanks for composing such an intriguing article on this point. This has truly made me think and I plan to peruse more Tomatillos

All the contents you mentioned in post is too good and can be very useful. I will keep it in mind, thanks for sharing the information keep updating, looking forward for more posts.Thanks Garcinia Cambogia

Thanks for sharing this information. I really like your blog post very much. You have really shared a informative and interesting blog post . Cowpeas

Excellent effort to make this blog more wonderful and attractive. Green Tea

All the contents you mentioned in post is too good and can be very useful. I will keep it in mind, thanks for sharing the information keep updating, looking forward for more posts.Thanks Peppermint Tea

This is very educational content and written well for a change. It's nice to see that some people still understand how to write a quality post! Monk Fruit

This post is not just informative but impressive also. The post is so convincing that it created an urge to choose Assignment help services. https://www.myassignmenthelpau.com/

This really interesting post. Thanks for sharing! spotify web player- https://spotify-webplayer.com

Is really Vectors which are willing just before each other at 90 degrees are orthogonal vectors?

Regards: Sophia Law Essay Writing Services

Thank you for the helpful guideline and tutorial! It's very hard but I feel I can solve it after reading your post. instagram Hope to see more posts from you.

<a href="http://itechbeat.com/vulkan-runtime-libraries-should-i-remove-it/">Vulkan Runtime Libraries Should I Remove It?</a> On picking an orthogonal vector (and combing coconuts)

<a href="http://www.Pharma-wisodm.com">Pharma wisdom</a>

I regularly visit your site and find a lot of interesting information. Not only good posts but also great comments. Thank you and look forward to your page growing stronger. https://webnovel.online

That Can help You To Find Best sattamatka Datefix Game For Kalyan and Main Mumbai Matka Games.

You have such informative, eye-opening information. Thanks for sharing this tips! In the meantime, you can see https://s-bobet.com/ site for some sports updates

The above post has given reliable and genuine information about Assignment Help Australia. Looking forward to avail their eminent services. http://www.firstassignmenthelp.com/

Excellent post. I was checking continuously this blog and I'm impressed! Very useful information particularly the last part :) I care for such info a lot. I was seeking this certain info for a long time. Thank you and good luck. bullet force

Thanks for guiding me. I can understand the vector clearly now hotmail

I am so happy to read this. This is the kind of manual that needs to be given and not the random misinformation that's at the other blogs. <a href="https://www.electronicsassignments.com/">Electronics Engineering Online Assignment Help</a>

Really i appreciate the effort you made to share the knowledge. This is really a great stuff for sharing. Keep it up . Thanks for sharing. https://engineeringhomeworkhelp.xyz

http://nhacaiuytin988.com/em-gai-duong-mich-tung-anh-khoa-than-danh-bai-online/ http://betbongda988.com/danh-sach-cau-thu-tham-du-giai-aff-cup-2018/

Just admiring your work and wondering how you managed this blog so well. It’s so remarkable that I can't afford to not go through this valuable information whenever I surf the internet! hualien restaurants https://www.islandlifetaiwan.com/the-best-hualien-restaurants-the-locals-perspective/

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. hualien beach https://www.islandlifetaiwan.com/hualien-beach-guide/

I can’t imagine focusing long enough to research; much less write this kind of article. You’ve outdone yourself with this material. This is great content. Anyror http://onlinesatbara.com/anyror-anywhere-gujarat-land-record/

These are some great tools that i definitely use for SEO work. This is a great list to use in the future.. sherline spindle upgrade https://commondatastorage.googleapis.com/taig-sherline-mill-lathe/taig-sherline-headstock-upgrade/index.html

I love the way you write and share your niche! Very interesting and different! Keep it coming! https://www.snowtimes.de/

It is imperative that we read blog post very carefully. I am already done it and find that this post is really amazing. online discounted deals https://onlinediscounted.com

Good article, but it would be better if in future you can share more about this subject. Keep posting. https://pos4less.de https://pos4less.de/Thermorollen.html

This is really a nice and informative, containing all information and also has a great impact on the new technology. Thanks for sharing it Enjoy Mexico top desinations https://enjoymexico.net/top-mexico-destinations/

This is very educational content and written well for a change. It's nice to see that some people still understand how to write a quality post! Enjoy Mexico Villa Rentals in Punta Mita https://enjoymexico.net/punta-mita-villa-rentals/

Thanks for sharing the info, keep up the good work going.... I really enjoyed exploring your site. good resource... bohs p405 https://www.natas.co.uk/4-day-p405

Positive site, where did u come up with the information on this posting? I'm pleased I discovered it though, ill be checking back soon to find out what additional posts you include. Enjoy Mexico Villa Rentals in Cabo San Lucas https://enjoymexico.net/villa-rentals-cabo-san-lucas/

http://percentagecalculator.wiki/ Je vous remercie de l'information! Je cherchais et ne pouvait pas trouver. Vous me aidé!

Its a great pleasure reading your post.Its full of information I am looking for and I love to post a comment that "The content of your post is awesome" Great work. walami trail https://www.islandlifetaiwan.com/tours/walami-trail-riverside-hot-springs-and-waterfalls-tour/

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post. zhuilu old trail https://www.islandlifetaiwan.com/tours/jhuilu-zhuilu-old-trail-tour-with-qingshui-cliffs/

I'm glad I found this web site, I couldn't find any knowledge on this matter prior to.Also operate a site and if you are ever interested in doing some visitor writing for me if possible feel free to let me know, i am always look for people to check out my web site. <a href="https://thehydeofficial.tumblr.com/">The Hyde floor plan</a>

I high appreciate this post. It’s hard to find the good from the bad sometimes, but I think you’ve nailed it! would you mind updating your blog with more information? The Hyde floor plan https://thehydeofficial.tumblr.com/

it's friday https://192168ll-ip.com/

project lead is allergic to changes... https://192168ll-ip.com/192-168-l-254/

Easy way for Instagram users How to delete Instagram account in 2018

Hi there! Nice stuff, do keep me posted when you post again something like this! Vidare till bloggen nu http://jazzhills.se/category/webbtips/

Like this specific article went over, you see that there are a couple

of approaches to brighten your teeth. Despite the fact that teeth get

consistent consideration, they can at present be stained period.

Execute the infor

services/self-employed/ ">Self Employed Self Assessment Tax Returns</a>

I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article. Vidare till hemsidan nu http://malmofisk.se/tag/tips/

Hey friends fi you want to play sudoku for free online then must try https://sudokuonlineplay.net/ its best sudoku website ever.

I love seeing websites that understand the value of providing quality information. Thanks for sharing. https://www.careerschedule.com/

This article was written by a real thinking writer. I agree many of the with the solid points made by the writer. I’ll be back. <a href="https://www.islandlifetaiwan.com/spend-the-day-at-liyu-lake/">Liyu Lake</a>

I am glad you take pride in what you write. This makes you stand way out from many other writers that push poorly written content. Liyu Lake https://www.islandlifetaiwan.com/spend-the-day-at-liyu-lake/

I am glad you take pride in what you write. This makes you stand way out from many other writers that push poorly written content. Liyu Lake https://www.islandlifetaiwan.com/spend-the-day-at-liyu-lake/

I'm inspired, I should state. Entirely should I experience a

weblog that is both educative and engaging, and oh my goodness,

you may have hit the nail for the head. Your idea is remarkable;

the agony is something that insufficient people are talking

cleverly about. My business is glad we discovered this at my

search out something in regards to this

">https://besthempdeals.com/</a>

thanks for the information, great job <a href="https://digitalwaysoft.com/digital-marketing-training-in-karimnagar/"> Digital Marketing Training in Karimnagar </a>

I found your this post while looking for some related data on

blog search...Its a decent post..keep posting and refresh the

data

">https://realagecbd.com/</a>

I'm a decent implied for all articles or blog entries, That I

emphatically relished, We'd to a great degree pick much more

records identified with the, because of the reality it is in

reality okay.,

">https://thebestpurecbdoil.com/</a>

I am glad you take pride in what you write. This makes you stand way out from many other writers that push poorly written content. Mer om Wordpress CMS system http://fyranyanseravrott.se/

This is really a nice and informative, containing all information

and also has a great impact on the new technology. Thanks for

sharing it Home

">real estate offices in los angeles</a>

I am Ted Johnson, Excellent and nice post. It will beneficial for everyone. Thanks for sharing such a wonderful post. Avail No Dissertation Help UK from certified PhD writers. It is extremely helpful for me. email us at:- info@ukdissertationhelp.co.uk Phone Number :- 020 8144 9988 visit here:- http://www.ukdissertationhelp.co.uk/

I have read your article, it is very informative and helpful for me.I admire the valuable information you offer in your articles. Thanks for posting it.. Nicole Bray https://www.nicolebrayrealestate.com

I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business. Milwaukee SEO Company https://www.milwaukeeseocompany.com

I can see that you are an expert at your field! I am launching a website soon, and your

information will be very useful for me.. Thanks for all your help and wishing you all the

success in your business. check this site

portalId=27043198&postId=27667956&portletAction=viewpost ">http://www.centralislip.k12.ny.us/blog/One.aspx?

portalId=27043198&postId=27667956&portletAction=viewpost </a>

this is really nice to read..informative post is very good to read..thanks a lot! Home Health Care Boca Raton http://homehealthcarebocaraton.com

I'm just excited your offer. It is brilliant to discover the majority explain in words away from your mindset along with skill for this important issue vicinity are actually adequately determined

advisor-accountant-services/self-employed/ ">Self Employed Tax Return Accountants Crawley</a>

I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often. Bücher für plastische Chirurgie https://www.books-plastic-surgery.com/

I haven’t any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us. swallow grotto https://www.islandlifetaiwan.com/10-best-trails-in-taroko-gorge-national-park/