Why Is Just Intonation Impractical?

Question: I've read about the debate of "just intonation" vs 12-tone equal temperament. And nowhere it was clearly stated why just intonation is impractical. Here are my assumptions. Please let me know if I am correct.
Just intonation frequencies are based on the harmonic series. A fundamental tone is picked and then all of its harmonics are transposed within one octave (that is, in the range of the first two harmonics). The first N harmonics account for 12 different notes in that range.
However, if an instrument is tuned with the frequencies obtained in the above manner, the instrument only sounds good in one key. In other keys it sounds out of tune (because the frequency ratios for the intervals are not simple integer fractions like 3/2). For that reason the 12-TET tuning system was developed, so that the same strings can be reused in all keys without sounding out of tune (and without the need to re-tune the instrument when changing the key).
What is not clear is why this is the case. The Harmonic series should produce harmonic sounds. At first it looks they don't and therefore a "hack" is needed.
My guess (please refer me to a source explaining it) is that the harmonic-series-derived tones sound good in the key based on the tone that was chosen for the fundamental frequency for a given series. So if we choose C3 as the fundamental frequency, all intervals will be OK in C-major, but will be out-of-tune in A-major. For them to "work" in A-major, we need to pick A3 as the fundamental frequency and calculate and transpose the harmonics. Thus the 12 (or 24, or whatever) notes will have slightly different frequencies depending on the key. The compromise of 12-TET is made so that an instrument doesn't need hundreds of keys/strings in order to play in multiple keys.
Is that correct?
Comment: @WheatWilliams Speak for yourself, Wheat. I find the math very elucidating. I'm not suggesting the OP shouldn't listen to recordings or experiment as you suggest, but some of us find math to be a powerful tool for understanding these matters.
Comment: In the context of computer generated music, it can be more practical now than ever.
Comment: Note that the definition of what is "A Major" (relative to whatever is your C note) **itself** changes under just intonation. The circle of fifths breaks and you actually have an infinite number of keys.
Comment: Wendy Carlos had a computer-based synthesis system that allowed rapid updating of the tuning tables.  She wrote and recorded many pieces in just intonation.  With this system she could start in C major just intonation and suddenly modulate to F major just intonation by adjusting the pitches.  She could go around the circle of fifths in just intonation!  The results can be heard on her 1986 release "Beauty in the Beast".  (Yes, it's really a spiral of fifths; the C you end up on is not quite the C you started on.)
Comment: In addition to reasons other answers provided, your initial question has made a faulty assumption in the first place which no one addressed. Just intonation scales are based on rational ratios, but not on the harmonic series. They are much more complex than that to achieve more equidistant pitch distribution than the harmonic series. However, even if scales were simply built upon the harmonic series, the same issue of powers of prime numbers never equating to powers of other prime numbers when multiplied out as products of tonal steps would still arise.
Comment: You are not going to get very far in your understanding of these matters by reading about the mathematics. You need to find some recordings to listen to or some electronic virtual instruments to experiment with.
Comment: @Dave exactly. I'm asking this in a distant relation to my http://computoser.com project (currently it uses MIDI, which is based on the 12-TET, but it's worth knowing the possibilities)
Comment: TL;DR - If you limit yourself to simple fractions, most intervals can be tuned in multiple different ways, and choosing one way will often leave something out of tune elsewhere.
Answer: Yes, you're right.  As for why the harmonic series doesn't produce notes that work in all keys, the simple answer is that the math just doesn't add up.
Let's work out the math for just intonation: Suppose you choose X Hz for the fundamental frequency and go from there.  Then the octave above the fundamental should have frequency 2X Hz.  Meanwhile, the perfect fifth above X will have frequency 3⁄2 X Hz.  The perfect fifth above that will have frequency 3⁄2 * 3⁄2 X = 9⁄4 X Hz.  Continuing on the cycle of fifths, you can easily see that every pitch generated this way will have frequency (3⁄2)n X Hz for some exponent n.
If there are twelve tones in the chromatic scale, then (3⁄2)12 X should be some whole number of octaves above X, i.e. (3⁄2)12 must equal a power of two.  But this is impossible because no power of 2 can have 3 in its prime factorization, as all powers of 3⁄2 must have.  Indeed, if you don't insist that the chromatic scale have twelve tones, you still can't make the math work: (3⁄2)n != 2m for any positive integer values of n and m.
Is it close, though?  Not close enough. (3⁄2)12 = 129.74, and the closest power of 2 is 27 = 128.  In practical terms, this means that the A one octave above A440 is 440 * 129.74 / 64 = 892 Hz, which is definitely audibly distinct from the pure 880 Hz you'd expect.  The math just doesn't work—just intonation cannot produce a set of pitches that work well in all keys.
Comment: @Bozho Well, in a sense, this is exactly what string players and vocalists do.  Since a violin has no frets, the player can adjust her intonation as needed for each note, taking the context of the harmony into consideration.  When a violinist plays an F# in the key of G, she'll play it slightly shaper than if the key is, say, A.  But for fixed-pitched instruments like keyboards, this quickly becomes impractical.
Comment: All wind instruments have the ability to fine-tune individual notes through a combination of techniques, in fact. Orchestral players are always on the lookout for 5th and 3rd chord members to raise or lower, respectively, to their justly-tuned equivalents, even if they're not explicitly marked "-14c".
Comment: Actually, the real problem behind tempering is not how poorly just perfect fifths (via the third harmonic) line up with octaves (via the second harmonic), but how poorly just major thirds (via the fifth harmonic) lines up with octaves.  To see this, note that the equal-tempered fifth is only a few cents short of just while the equal-tempered major third is about 14 cents greater than just.  The essence of the reasoning is the same, though.
Comment: thanks. It can't, if you start from one fundamental frequency. But if you start from multiple fundamental frequencies, and end up with hundreds of keys, it will potentially be in tune for e very key. Provided there's someone able to play it :) Right?
Comment: This answer is not quite correct.  It does not address the question's incorrect premise.  In fact, it is not necessary to consider more than one key to show why it's necessary to temper a keyboard.  The correct answer is "just intonation cannot produce a set of pitches that work well in any key."
Comment: The mathematical explanation offered here is irrelevant - what you've shown is that in JI, B# is off from A natural (also it's off by a factor of 129.7^(1/7), not 129.7/64). The reason why a given set of JI pitches only work for a single key is that when choosing another root, the ratios are no longer correct. E.g. in a JI tuning based on C, the frequency of D (major 2nd) is 9:8 of the root, while Db (minor 2nd) is 16:15. Taking Db as the root, suddenly the minor 2nd (now D) is not 16:15 but (9:8)/(16:15) = 135/128, i.e. 1.054 instead of 1.066.
Comment: I meant "G## is off from A"
Comment: @staafl you repeat the incorrect premise: "The reason why a given set of JI pitches only work for a single key...."  In fact, a given set of JI pitches only works for a subset of chords of a single key.
Answer: I want to make an addition to all these excellent answers.
With just intonation, it's not possible to make all the chords just. Not even in a single key.
Let's look at the common just major scale based on I, IV and V just major triads:
C 1:1
D 9:8
E 5:4
F 4:3
G 3:2
A 5:3
B 15:8
In this scale, I, IV, V major triads (4:5:6) and iii and vi minor triads (10:12:15) are just.
But ii minor triad is out of tune: D-F interval is 32:27 instead of 5:6. This is ~294 cents vs 316, which is worse than the equal tempered 300.
Worse yet, D-A interval is 40:27 instead of 3:2; 680 cents vs 702, again way worse than the equal tempered 700.
One way to fix it is to flatten D down to 10:9 but this will break the V major triad. There's simply no way of making them all just without adding more notes. Not even in a single key.
Comment: I was scrolling down to add an answer making this point when I saw this answer and upvoted it instead.  It deserves more upvotes, pointing out as it does the incorrect premise that "if an instrument is tuned with the frequencies obtained in the above manner, the instrument ... sounds good in one key."  In fact, the instrument sounds good only in certain *chords,* which don't even give you all the chords you need for one key.  For example, if you take A as a fifth above D, and F as a fifth below C, then your F-major chord will have a very high (and definitely not just) third.
Comment: In Pythagorean tuning, you can fix the "wolf" intervals by having separate keys (or frets or holes or whatever) for enharmonic notes.  So, for example, the P5 is in 3:2 ratio, but the enharmonic d6 is 262144:177147.  But this *doesn't* work in 5-limit JI because "the same" interval needs to have a different frequency ratio depending on context: If the M3 should be in 5:4 ratio, then M2 needs to be 9:8 half the time and 10:9 the other half.
Comment: @Some_Guy four fifths above X is E, and a fourth and a fifth above C is ... C.  The note A is either a fourth and a third above C, or three fifths.  With this in mind, your comment is otherwise correct.
Comment: Great answer.  If you are in the just intonation key of C, you can derive the note A in 2 ways: 4 fifths above C, or a fourth and a fifth above C.  And they're out of tune with each other: you'll either have an in tune F major chord or an in tune D minor chord but never both!
Comment: Ok, but surely if a composer is choosing a just intonation scale for a piece of music they would design it so that all the chords they wish to use sounded good; @phoog in your example why not just add another interval to your scale so that you can have a pure and just F-major chord? Surely thats part of the point of using such scales, breaking free of the limitations of 12 tones.
Comment: @Adamski you presume that composers choose scales for their pieces; in the vast majority of cases that's not how it works.  If you're talking about infinitely variable pitch such as with the human voice or an unfretted string, then you can sing or play a different pitch for A depending on whether it's the third of an F-major chord or the fifth of a D chord.  If you want to call that an additional "note" in the "scale" then be my guest.  And sure, for some people who use those scales that may indeed be the point of doing so.  But you can't play such a piece on a traditional 12-tone keyboard.
Comment: @phoog absolutely, don't know what I was saying in that above comment!
Answer: Alex Basson has given you a great introduction to the mathematics. Let me approach the answer from a different perspective, that of the performing musician in a historical context.
Setting the mathematics aside, to put it simply, just intonation is what happens when you have a group of singers performing a capella, or a string quartet, or any other ensemble of monophonic instruments that can inflect or bend their pitch. But as soon as you insert a conventional piano or guitar (which are tuned to 12-tone equal temperament) into the ensemble, all the other instruments and performers will shift from just intonation into equal temperament so as not to clash with the guitar or piano. Singers and string players don't consciously think about it; it just happens.
There are also instruments in existence that play only in pure just intonation. These are instruments that can only play one scale in one key, and no extra notes outside of that. They include the natural trumpet or bugle (which have no keys, no valves, and no vent holes), or certain designs of the recorder, or the bagpipes.
Just intonation is extremely impractical for instruments that play chords (guitar or piano), or any instrument with fixed pitches which cannot bend, such as vibraphone or marimba.
How many keys do you want in an octave on your keyboard? In the Baroque period, 12-tone equal temperament had not yet been invented. Although the early harpsichords and organs had 12 notes to the octave, they used various tuning schemes that were based on just intonation. Each instrument could only be played successfully in a few keys with the tuning scheme in use.
To expand on that, innovative designers in the 1500s and 1600s built a few organs and harpsichords with between 14 and 36 different pitches/keys within one octave to be able to play in something closer to just intonation in many keys.
To say that learning to play a keyboard with that many keys in an octave was an added difficulty to the keyboardist is an understatement. It also meant that harpsichords and organs had to have extra strings and extra pipes to play the extra pitches, adding significantly to the cost and the mechanical difficulties of building and maintaining the instrument.

This problem was largely resolved when the "Well-Tempered" tuning was invented and subsequently championed by J. S. Bach. Later on, true 12-tone equal temperament was developed. Around this time, most keyboard musicians lost interest in keyboards with extra keys/pitches for approximating just intervals in various keys.
In the modern era
there have been several designs for a just-intuned keyboard for electronic musical instruments, with many more than 12 keys/notes in an octave.
I know of one electric guitarist, Jon Catler, who plays guitars built with extra frets to make 31 equal-tempered notes in an octave. His purpose is to play conventional tonal music that enable a skilled performer to get close to just-intoned intervals in many keys; he's not composing and playing exotic non-Western scales or music. Lately he's been recording on a new guitar he designed with 64 notes in an octave that he says achieves just intonation in all keys.
Below are pictures of two guitar designs which he sells, and below that is a video demonstration, playing a guitar of yet a third design.

Not many guitarists would want to learn to play one of those instruments. Take a close look at those frets on those fingerboards and you will see why just intonation on a guitar is impractical for anybody but a select few avant-garde musicians who want to go to the tremendous trouble to develop a very complicated playing technique in the name of creating more pure intervals.
Comment: Just one comment from a percussionist: vibraphone pitches actually can be bent. The general technique for it is to strike as usual and then press in on the bar with a rubber mallet, starting from a node (where the string passes through the bar) toward the center. This lowers the pitch, and as you would expect, dampens the sound and cuts off sustain sooner than usual since the vibration is being stopped by contact between the bar and mallet. I am unaware of a technique for bending upward. It is also possible on marimba but the effect is much less noticeable.
Comment: A comment re recorder - the pitch is somewhat dependent on breath pressure. More pressure sharpens the note; less flattens. Soft-wood recorders (e.g. pear, maple) are more prone to changing pitch than hardwood instruments (e.g. ebony). In our consort we use breath pressure extensively to tune chords to just tuning.
Answer: I have come across an even more astonishing system for producing pure intervals on a guitar. A Turkish guitarist, Tolgahan Çoğulu, has patented a system for building a guitar that has channels under each string position that allows the quick installation or removal of any number of tiny partial frets, each one string-space wide, which can be adjusted up or down to any arbitrary microtonal position by hammering on them with a small "spudger" tool.
The performer would be able to recalibrate all the fret positions and intervals of the entire fingerboard any time the performer wishes to play in a different tuning system.
Apparently it was developed for the Turkish style of music called maqam, which uses quarter-tone intervals not found in Western music. But the luthier also demonstrates its use in Western music that uses equal temperament or meantone tuning systems, and mentions that it would be useful for playing Western Renaissance or Baroque pieces.

In these two videos, he provides a technical description, narrated in English, and demonstrates the use of his instrument in playing excerpts from several different traditional compositions from different historical periods in Turkish and Western music.

His website indicates that he will build and sell many styles of guitars and other fretted instruments (not just classical guitar) by special order, but few details are provided.
Comment: That's clever and completely awesome. On the viol we use tied-on frets, but they're not as effective as the big raised solid frets on a modern guitar, so this is a really neat solution to a problem most people don't even know exists.
Answer: Just intonation does produce harmonic sounds; perhaps the most harmonic sounds possible. You are correct that for a Justly tuned system to work, then each of the tones that you use will need to be adjusted relative to the current tonic. Because of this, you are correct to think that there will need to be many different 'flavors' of each note, depending on the context. There has been enormous work done in this field many composers and scientists over many centuries. The source I choose to share here is the work done by the American composer Ben Johnston. This is an example of the notation he used to distinguish between each specific note, and they are created by performing simple mathematical operations (basic arithmetic).
I will give a brief explanation of Johnston's system here, and relate it to your question. Johnston's motivation was to pretend as if Twelve-Tone equal temperament never became a popular trend: he pretended that composers had thought it important to explicitly describe intonation through their notation system. Of course, this is not what happened, so he had to create a system of his own. You could think of his system as a way to get from one note to another without having to explicitly define EVERY NOTE that one would need to use. This might seem confusing, so let me define something that should be familiar: the Major scale.
The major scale is a pattern of intervals that produces notes that can be combined melodically and harmonically to make music. There is a distinct pattern between each note in the scale that you may be familiar with. If our scale is in C major, and our notes are
c d e f g a b c

then the intervals between each note will follow the pattern of whole (W) and half (H) tones below.
c d e f g a b c
 ^ ^ ^ ^ ^ ^ ^
 W W H W W W H

This pattern holds if you are using a piano, where each whole tone is 'equal' to every other whole tone. BUT in just intonation, this assumption does not hold. In just intonation you define EXACTLY what the value of a whole tone is, as well as EVERY OTHER INTERVAL YOU USE!
If we were going to follow Johnston's model, then we would define the intervals using the simplest pieces possible. For musical intervals, that means ratios between whole integers with low values. The reasoning behind this is because that is how a Harmonic series works. From your question I know you are familiar with this concept, so I wont describe it much other than saying that if you want to make a scale with the most harmonic potential, then you will pick intervals from the lowest notes of the harmonic series (shown by order of appearance here):
The Octave: 2/1,
The Perfect Fifth: 3/2,
The Perfect Fourth: 4/3,
The Major Third: 5/4,
The Minor Third: 6/5

These five intervals are enough to make simple harmonic chords! We begin with the octave. Then we split that into two intervals: the Perfect Fifth, and the Perfect fourth. Next, we split the perfect fifth into two pieces: the Major third, and the Minor third (notice how the numerator of the previous ratio becomes the denominator for the next ratio, and the numbers are growing by a succession of 1). Now we just need to split the thirds into smaller intervals so that we can have melodies that can go up and down smoothly.
One of the simplest ways of doing that is to build Major chords that can be 'stacked' into each other. Why major chords? Because it's a fundamental chord within the harmonic series.
1/1 - 5/4 - 3/2

So if we use the major chord as a pattern, and copy it a few times, we can produce a set of the notes within the major scale. By doing this, we're making a very simple scale, and only using three prime numbers: 2, 3, and 5. (Johnston's system can accommodate prime numbers up to 31, and anyone could theoretically extend it to include as many primes as they wish).
If we use the first three intervals of the harmonic series for the parameters of copying the Major chord, we will get a good amount of pitches to make our scale. We start by shifting the pattern up to start on the pitch a perfect fifth (the ratio 3/2) above the tonic.
                1/1 - 5/4 - 3/2
                            3/2 - 15/8 - 9/8

Then we copy the pattern onto the pitch a perfect fifth below the tonic (equivalent to a perfect fourth above the tonic, but it is less cluttered to go below for now).
    2/3 - 5/6 - 1/1
                1/1 - 5/4 - 3/2
                            3/2 - 15/8 - 9/4

Now let's name the pitches to give some clarity. If 1/1 is C, then:
     f     a     c
    2/3 - 5/6 - 1/1
                 c     e     g
                1/1 - 5/4 - 3/2
                             g      b     d
                            3/2 - 15/8 - 9/4

or
 c     d     e     f     g     a      b     c
1/1 - 9/8 - 5/4 - 4/3 - 3/2 - 5/3 - 15/8 - 2/1

This is a major scale derived from C (notice how the ratios from the F chord are now transposed, meaning they are now 'above' C, and the D is transposed down an octave). To complete this explanation, we need to recall the first description of the intervals between and equally tempered scale, which was composed of two intervals: whole and half tones. The scale we just (pun) made is Justly Tuned, so we actually get two types of whole tones! The consecutive intervals of the Just Major Scale is:
    c  to  d  to  e  to   f to  g  to  a  to b  to  c
1/1 -  9/8 - 10/9 - 16/15 - 9/8 - 10/9 - 9/8 - 16/15

Why is this important? Well it shows that Just intonation, as you noticed, introduces a lot of variety when it comes to intervals. This means you need to pay special attention to how each note relates to every other note. This is hard to do on paper, but composers like Ben Johnston and Toby Twining have been doing it for many years, and so they have much to teach those willing to listen.
In conclusion Bozho, it is not unpractical to compose music using Just Intonation. That being said, it is not easy. If more composers chose to take up the challenge, then we might develop more tools to make the job more efficient. For now, there is still much work to be done.
Cheers!
Comment: Note that your A, 5/3 above C, is also (5/3)/(9/8) = 40/27 above D rather than 3/2.  This makes D chords sound particularly awful.  The just fifth above D is 81/80 above that (this ratio is known as the *syntonic comma),* and it makes F-major chords sound pretty bad.  This explains the need for temperament even in a seven-key-per-octave keyboard intended to play diatonic music in only one key.
Comment: @phoog Thank you for pointing that out. I was trying to imply this issue, but forgot to go into its implications in my answer. You're right that this issue *could* be solved by using a temperament, but it could also be solved by knowing when to lower D by the syntonic comma (or raise A). Temperament is a solution that assumes a lot, namely, that we are playing an instrument with a fixed set of pitches like a piano. Choirs and string quartets don't have these limitations, and neither do computers, so If our goal is to write music for these instruments, we can choose an intonation freely.
Comment: +1 - From my perspective, this is an important answer. The question assumes JI is "impractical," but it depends on your goals. Modern Western ears are used to 12-TET and compromise temperaments. Many other possible scales exist, including JI scales that have a great variety of intervals. Yes, some intervals will sound "bad" particularly when used harmonically, but (1) harmony isn't everything in many types of music, and (2) the varieties of sounding "in-tune" vs. "out-of-tune" give an entire different dimension to music, as folks like Johnston and his teacher Harry Partch well understand.
Comment: "Temperament is a solution that assumes...that we are playing an instrument with a fixed set of pitches": note that my comment about the necessity of temperament is still in the context of a keyboard. In fact, temperament is a solution to the problem of playing an instrument with a fixed set of pitches, but most people don't realize this and try to use the concept when it's unnecessary, such as with voices and strings. But even with voices and strings you have comma pumps, which require some sort of compromise, the most practical of which are generally temperament or at least temperament-like.
Comment: In saying that I'm thinking of Josquin's _Ave Maria,_ where you either have to modify certain sustained notes or use tempered intervals if you want to end on the same pitch that you started on.
Answer: Using a keyed instrument with Just Intonation creates a bunch of puzzles that need to be solved.  You are either faced with observing limits on navigating from place to place, or doing "comma pumps" (equating near by intervals, or bend/vibrato between them because they are close enough).
The problem isn't really Just Intonation though.  It's caused by trying to play on an instrument that has a set of keys (and notating it as such), rather than being continuous.  In other words, named keys may be a bad interface for Just Intonation.
On a fretless instrument, JI is not only practical, but the sensible way to navigate.  Stopping a string to an existing note and playing a seventh harmonic there (ie: notePitchInHz * 7) is completely natural and can be described easily enough, but that note doesn't have an obvious 'name'.
Besides just labelling keys, Just Intonation might be the only viable way of doing relative pitch in a general way:  Imagine that you had buttons on a monotonic instrument labeled like: /2, *2, /3, *3, /5, *5 ....
People already use pitch lattices which were derived in this way; like horizontal is *3, vertical is *2, etc.
Answer:
For them to "work" in A-major, we need to pick A3 as the fundamental frequency and calculate and transpose the harmonics.

This is one of the bigger misperceptions about just intonation. A perfect fourth is not an overtone (it is an undertone), so if you want to play music in which the perfect fourth plays a significant role — which, let's face it, is pretty much anything in Western music — then you need to use a harmonic series starting down at the fourth.
That is, if you want to play in the key of A, your fundamental frequency should be D, not A. That will give you a nice, harmonic D chord.
I see a lot of comments here focusing on fifths not closing on octaves, but it's not obvious to me why that should matter. Most songs — especially in folk music — don't modulate all over the place. They stick to chords near the home key, and as long as those are in tune the rest don't really matter.
For example, if you're playing in C (using the harmonic series of F₀), you'll have perfect tuning for the intervals in the chords C⁷, F⁷, G, A, Am, Em, and Bm. The fifth of the Dm chord will be off by a syntonic comma (around 21.5¢). I don't know about you, but I can play a lot of songs using those chords.
I worked up a spreadsheet with the harmonic tunings I've been using if you'd like to give them a try:
https://docs.google.com/spreadsheets/d/1qTgPaLqDd8J315zxJ1ub5pbDWnlDHkJ5CNVYa_5JrnA/edit#gid=0
Comment: "I see a lot of comments here focusing on fifths not closing on octaves": it obviously should matter if you're tuning a 12-tone keyboard instrument.  There lies the difference between "intonation" in the phrase *just intonation* and "temperament" in the phrase *equal temperament* (or any other).  Your list of seven chords, though, uses several pitches that are not readily found in the overtone series of F, namely B-flat, C# and F#.  Also, in many contexts, the problem is not only harmonic intervals but melodic intervals, for example if you've got the common bass line C-A-D-G-C.
Comment: B-flat (in the tuning I'm currently using) is harmonic 21 of F — the harmonic seventh of C. C# is harmonic 25 (a major third above A), and F# is harmonic 135 (a major third above D): all within four odd factors in a 7-limit tuning.
Comment: "B-flat (in the tuning I'm currently using) is harmonic 21 of F — the harmonic seventh of C": this means that the ratio of the fifth in your B flat chord is 32/21 instead of 3/2.  Okay, you might not need a B flat chord in C major, but then again you might.  The D-to-A fifth is a more significant problem.  There may be a lot of songs that don't require `ii` or `V/V`, but it is a prominent chord in many common progressions, certainly more common than `vii`.
Answer: Here is a table that I have adapted from one in Wikipedia that illustrates how just intonation differs from 12-tone equal temperament.
In modern instrument tuning, an octave is divided into 1200 cents. There are 100 cents in an equal-tempered half-step, and all half-steps are equal in their distance apart.
However, in just intonation, not all half-steps are the same size. This table explains the discrepancies, and shows you just how out-of-tune certain musical intervals are on the 12-tone equal tempered piano, organ, synthesizer or guitar.

As you can see, in 12-tone equal temperament, all intervals except the octave are slightly out-of-tune. The intervals that are the most noticeably out-of-tune are the tritone, the minor third, the major sixth, the major third, and the minor sixth.
Also note that just-intoned intervals cannot be expressed as integer values of cents in the first place. The cent is a convenient mathematical measuring unit based on 12-tone equal temperament. So the unit of the cent really has nothing to do with pure frequency ratios.
Comment: Here's a huge list of 700 pitches within an octave, ordered by frequency difference, with their respective names, when they exist (Just Intonation people seem to don't care much about names): http://www.kylegann.com/Octave.html and here is the same table with the actual decimal representations, instead of just fractions: https://a3c8e3f1dc0bac4f596b4c29df042f945b58fc7e.googledrive.com/host/0B6XDAfFbY5MpNGhiMmpLc2Ziams/elm/anatomy%20of%20an%20octave.html
Comment: How are you defining that tritone? Is it a diminished fourth or an augmented fifth? What is the just-intonation ratio for a tritone? 45/32? 25/18? 36/25?  In other words, in just intonation, not all tritones are the same size, either.
Answer: A relatively new company in Sweden, True Temperament, retrofits electric, acoustic and classical guitars with new necks or fingerboards with heavily modified fret positions that are designed to improve intonation.
If I understand their intent, their "Thidell" design is for playing with something closer to pure intervals, but chiefly in the most common guitar keys of E, A, and D. The further you get away from those keys, the less accurate the intonation gets.

They also have several other designs for producing other kinds of intonation more suited to other purposes. For instance, they make an entirely different fret layout for playing in the keys more commonly found in jazz.
This looks like a compromise that might work. I have not seen, heard or tried any of their necks or instruments but there are demo videos and audio on the web site.
The most extreme example is this special-order option, a fingerboard that they claim enables playing pure just intonation in only one key (again, if I understand the intent correctly -- all this is very complicated.)
Notice that there are 14 frets to the octave, because apparently (I have not worked through the music theory) certain chords require a sharper or flatter major or minor third than can be provided by only 12 fret positions. So based on the chord, you could choose a G# or an Ab which have distinctly different microtonal pitches, for example, depending on which pitch would produce the correct, in-tune interval in that particular chord.
Comment: Steve Vai likes these - I posted up something on these last year. I plan on getting one of my guitars retrofitted with a Thidel - just for fun
Comment: I always thought of this as compensated tuning (unique to the instrument), and not just intonation.

Is there an answer here that clarifies that?
Answer: The foundations of existing music theory were build when scientific data about sound perception were absent and they were inclined to number mysticism which source was  that
consonant music intervals correspond  division of string in ratios of  small integers.
Now the following facts are known:
-the sound signal of basic existing music instruments may  be considered  as sum of fundamental frequency and harmonics which frequencies are multiples  of fundamental frequency and which intensity decreases quickly in common case .
-the ear may be considered as bank  of strong overlapping band filters  which diapasons roughly correspond one music tone and hence ratio 1.122 (or  1/1.122=0,891)
-the sensation of dissonance  arises when simultaneous existing frequencies are in the same diapason. By it strongest dissonance sensation arises if their distance is ca ½ of semitone that is ratio 1,029)
It is possible with help of these knowledges  to come to following conclusions:
- intervals with ratios of small integers are consonant as for them and their first (strongest) harmonics ratious don't belong to dissonant  values. About their harmonics it is apparent  that the less numbers in intervals' ratios the greater  must be numbers of  notes' harmonics for attainment ratio of their their frequencies as by tone interval or less. But the greater numbers of harmonic the less their intensities and weacker the sensation of corresponding dissonance.
For example:
for 5 and 7  harmonics if interval is 3/2- 3*5/(2*7)=15/14=1.07,
 for 3 and 5  harmonics if interval interval  is7/4- 7*3/(4*5)=21/20=1.05
That is in second case more favorable for dissonances ratio is obtained for more strong harmonics (3and 5 instead 5 and 7).
The question  why just intonation is impractical  is very convincing considered in the article "Renaisance "Just information" Attainable Standard or Utopian Dream? ( http://www.medieval.org/emfaq/zarlino/article1.html  )
Yuri Vilenkin
Answer: I can strongly recommend reading Harry Partch's Genesis of a Music, in which he goes into depth on the history of tunings and the reasons for them. Out of this he derives his 43-tone-to-the-octave scale from an 11-limit just scale, and then talks about the instruments he had to build and adapt to play music in this scale, and the compositions he did using them, in detail.
The 43-tone scale is a compromise to produce a better compromise, but 43 keys in every octave is definitely not practical. You can find some of his music on YouTube, and I recommend listening to it, especially with the book in hand. I recently found a performance of Delusion of the Fury which is very good and very interesting indeed.
And I almost forgot: Terry Riley's The Harp of New Albion uses a piano tuned to a 5-limit chromatic scale. See http://www.ex-tempore.org/Volx1/hudson/hudson.htm for details.
Comment: Thanks! I'll edit this answer to better reflect your comment. (I went and checked -- he stopped at the 11-limit but talked about 13 in his book.)
Comment: If you Google "Genesis of a Music PDF" you will get hits.
Comment: I'll second the recommendation to read Partch.  It should perhaps be pointed out that Partch's 43 tone scale is not 43 tone equal temperament, but consists of (if I remember correctly) 13-limit just intervals.
Comment: I'm afraid I lost my copy of _Genesis of a Music_.  I'd love to read it again.  Partch was a funny guy but had some great ideas.
Answer: Just intonation is only impractical if you insist on having a scale of more than six fixed steps, with all the intervals being 5-limit just.  God and/or math doesn't work that way.
The most cogent way of putting it is this: no power of two is also a power of three, and no power of three is also a power of five.
Answer: One of the best microtonal instruments may be the slide guitar. Listen to Duane Allman play slide guitar, or David Gilmour play lap steel, or countless others.  Not only do they reach the tones between the notes, but I suspect that they are naturally gravitating to the just tempered notes as well. That purity is what makes skilled slide guitar players sound so sweet.
The key difference between slide and the aforementioned multi-fret guitars is that slide is an adaptive process that relies upon the player. And the player will naturally play what sounds "right".
Comment: Therefore, more generally speaking, all continuous tone instruments (cello,  violin, fretless guitar, bass...) have no problem addressing just intonation as well as equal temperment (?).
Answer: If you only think about the fixed frequency instruments, just intonation is not good for the instrument construction, there is good examples for the guitar above. There will be technical difficulties with a piano and other instruments too.
But for continuous variation pitch instruments, the just intonation will have more natural sounding.
There is a good example of what happen in the sound waves in this youtube video.

You can see that just intonation is stable.
Comment: What do you mean by "stable"? Many chord progressions will drift off pitch when played or sung in just intonation, depending on which adjustments one uses to achieve the just intonation.
Answer: It's a mathematical fact that this equation:
1.5^n = 2^m
has no solution for nonzero integer n and m.  Therefore, no sequence of just-intoned fifths, therefore, will ever reach an octave perfectly, no matter how far you go.  So there is no equal temperament scale, no matter how finely divided, that will result in one of the notes being a perfect true fifth.
Comment: This is, of course, also true of a sequence of any other integral intervals, not just perfect fifths.
Comment: @ScottWallace in particular, for the purpose of 5-limit just intonation, of major thirds, three of which do not equal an octave, and one of which does not equal four fifths (that is, there are likewise no solutions to the equation `1.25^p = 1.5^n * 2^m`).
Comment: @phoog - indeed.  As I've mentioned here before, it's God's fault, or that of mathematics (if there's a difference).  I guess we can consider ourselves lucky that it's still possible to make great music, even given this most basic of all spanners in the works.
Answer: I'd like to add to Cyco130's comments. One cannot always combine different intervals to get another useful interval. This has implications for tuning a guitar by ear (without using the frets). One starts with the E string and goes up a fourth to A giving a ratio of 4/3. Thence up another fourth to D yielding 16/9 and so on to G arriving at a ratio of 64/27. Now a different interval or a major third (5/4) up to B, giving a ration of 320/108 (reducible to 80/27). Finally another fourth to the high E string giving a ratio of 320/81. This ration is very close to 4/1, the ratio for two octaves.
Two musically correct paths to the "same" note do not lead to the same note. In the case given above, one may have nice intervals for C, G, and F chords but then the d minor chord is out of tune. The IV and ii chords have been treated as similar for centuries though (5-6 techniques).
Answer: Saying that just intonation is based on relationships in the harmonic series is just a glorified way of saying that just intonation is based on natural number ratios (because the harmonic series is all the natural numbers to infinity). The issue of just intonation is that nearly all music implies the use of more notes than are explicitly written, while most modern fixed pitched instruments revolve around only using 12 notes per octave. Because these implied extra notes are only 20-50 cents away from each other, 12TET was implemented to make it so that performers only had to keep track of 12 pitches per octave by roughly averaging out the extra notes that were fairly close to each other. The notes in just intonation that are a small distance apart are either notated with the same letter or are notated as enharmonic equivalents when using 12TET, which is where the misconceptions and confusion about just intonation begins. The truth about why it seems as though just intonation "doesn't add up" is that western notation is to blame. It is often the case that someone will set up a demonstration of how just intonation doesn't work, and then they'll either assume enharmonic equivalence, which is something that can only be assumed in equal temperament, or they won't distinguish Pythagorean ratios from 5-limit ratios (less common).
Comment: You can't really blame Western notation if people use enharmonic equivalence. That's not built into the notation. Was _is_ built into it is the meantone assumption, i.e. that a Pythagorean ditone is the same as a Ptolemaic major third. To express otherwise would require extra symbols like the + Ben Johnston writes before the upper note of a Pythagorean ditone.
Comment: The thing is that the use of those extra notes is not always desirable. I've heard the story of the choir using just intonation to get through a song and then ending the song with their tonic a few cents away from where they started. That's an example of an unwanted extra note. End up using notes that are 20-50 cents apart (or even a comma apart) and the people with absolute pitch will be the first to unfavorably notice...and the *American Idol* fans will be the second.
Comment: @leftaroundabout - that's basically saying it assumes the player sticks to one tuning system :-)
Comment: Enharmonic equivalence applies to any 12-tone keyboard, regardless of the temperament in use.  Whether it works depends on the temperament, of course.
Answer: "Why is Just Intonation Impractical?"
The true answer is: It is actually the most practical way to tune and generates the 12 ancient keys of music. When a 12 tone instrument is tuned properly to the correct 12 just pitches, you will have 12 beautiful keys to play in that are based on the laws of harmonics, and yes you can easily modulate between keys. Indeed this tuning is the real basis of the idea of "keys" of music. It has been "lost" since before the Renaissance. Strange as it may sound, several years ago I recovered it. Anyone who can do simple math and listen to examples of the sounds will see I am right.
For a concise summary of this with examples of songs played in the 12 ancient keys, go to Unfretted dot com to the Other Instruments Forum to the thread, 17 Tone Just Intonation Guitar and scroll to my posts that begin July 17, 2018 (ignore earlier).
My gift to anyone who's paying attention. Most of what you've been taught about just intonation is fiction. Tom M Culhane
p.s.  Ask yourself, where did the idea of playing music in various keys come from? Certainly not from "modern tuning". Equal temperament has no keys to speak of, they all have the same feel, as the proportions one note to the next are identical. It takes variety to have keys of music. Other tuning systems have variety, but they are based on make believe numbers. Just intonation, on the other hand, is based on real math. Whole numbers are the basis of vibration in the real world. For example the harmonics you hear when you tap on a guitar string at certain points. One of the flaws in the answers given here is the idea of expressing musical intervals in the singular sense, such as "the fifth". A properly tuned 12 tone instrument will have a variety of fifths. Indeed it is this irregularity that gives us the keys of music. But you need the correct pitches to make it all work. I have found them. They were sitting right under everyone's nose.
Comment: Please could you clarify why, if irregularity is needed, all the non-ET Baroque tunings don't provide it? And how you reconcile your claim "irregularity that gives us the keys of music" with your claim that there is only one set of "the correct pitches" that "make it all work"?
Comment: Your edit is made from a different account than that which posted the answer. You can use [this form](https://music.stackexchange.com/contact) to try and merge your accounts.
Comment: My post here that I made yesterday has already received an unfavorable vote. I want to stress to the readers that if you are willing to listen to my vids I referenced above that are played in various keys of 12 tone just intonation, you will see they are all playable and beautiful keys. Sometimes it takes courage to let go of dogma. A piano tuner once told me I will only have a couple playable keys if I tune my piano to just intonation. I proved him wrong, sent him samples of chords in each key. Haven't heard from him since. To learn you've been tuning pianos wrong for 30 years can be scary.
Comment: I didn't give the downvote, but it may have less to do with the information and more to do with the reference to an outside site. It's typically better to have the information *in the answer* in case wherever you're directing us goes down in the future.
Comment: To Rosie F: Plucking a string will cause it to sing, but tapping at points that divide the string into whole number divisions (just intervals) causes other notes to naturally emerge. There is a science to how Nature vibrates. In 12 tone tuning, the 7 pure just tones are fundamental to the real, original ancient tuning. But you need 5 more numbers. This is where everybody screws up. The key to recovering those 5 is to think in terms of whole numbers. When you see the pattern and punch them in, voila! Everything clicks into place like a wooden puzzle snapping together. The keys emerge.
Comment: To Richard: The answer would have been quite long that way. At my Tom M Culhane youtube I have 18 vids, most in ancient 12 tone. Try Sarabande and Wild Rider to hear it on piano (my elderly mom playing in slow mo). All the strings on piano resonate together with this tuning so the piano really comes alive. Digital piano can't compare, but to hear me playing simple songs in other keys try: Frosty, 42 Mood, Moon Castle, The Hour is Late, Walk Around the Fire. Read the descriptions. Also see Removable Fingerboards at the same forum mentioned earlier for yet more info.
Comment: Lastly: It's known the establishment spams forums to influence readers. So check things out direct. I've given you all what you need to now play music in tune. Piano tuners will tell you if they tune a third to pure (5:4) most people will think it's flat as ET thirds are so sharp. Hearing music in tune may take your system a bit of time to adjust to, to unclog from the blurry music you've heard all your life. The more you hear the ancient 12 keys the more you will like them. And you can expect real benefits to your health and minds. Best Wishes. Tom M Culhane  signing off
Comment: Summary: A progression of 2:1 octaves hits the number 128. A progression of 3:2 fifths ("circle of fifths") hits 129.746... How do the laws of harmonics synchronize numbers from different primes like this? Answer: variation of intervals aka The Keys of Music. The original just intonation tuning I have given you is an octave tuning, all 12 pitches have a 2:1 octave to them. 7 of the 12 pitches have a 3:2 fifth to them. 5 use other whole number proportions for the fifths. This is how it all clicks together, everything in balance.
Answer: The reason why a given set of just intonation pitches only work for a single key is that when choosing another root (i.e. modulating), the ratios of the degrees in the scale are no longer correct. For example, in a JI tuning based on C, the frequency of D (major 2nd) is 9:8 of the root, while E (major 3rd) is 5:4. Taking D as the root, suddenly the major 2nd (now E) is not a ratio of 9:8 but (5:4)/(9:8) = 10:9, so the major 2nd comes out flat.
Choosing different root notes produces more or less dissonant tunings and in fact some intervals work out correctly (e.g. taking the perfect fourth F, the new major second G is correctly at 9:8 ratio from the root), but only the original root works in relation to all pitches. This also applies to other modes than the major - an instrument tuned in just intonation can only properly play one set of modes. This situation is avoided in equal temperament because the pitches are a geometric progression and the ratios between pitches depend only on the number of steps between them.
There's also the problem with flats and sharps not being enharmonic - if we define F# as leading tone in G major, and Gb as the perfect fourth in Db major, their frequencies don't match - 'the circle of fifths doesn't close':
.
(image courtesy of http://jjensen.org/spiral5ths/Spiral5ths.html)
Doing the math you get F#:G = B:C = 243:128 = 1.898438 and Gb:Db = Db:Ab = Ab:Eb = Eb:Bb = Bb:F = F:C = C:G = 4:31; multiplying all the ratios and dividing by the closest power of 2 gets you Gb:G = 4.36/4 = 1.872885 - so you can't have true Db major and G major scales using the same 12 chromatic pitches.
1 This is fudging it a little; in just intonation, the pitch of any note, and its ratio to any other, depends on the question "in which key?", and the ratio Gb:G doesn't make sense in any case since no key contains those two notes.  Here we're talking about the major keys of the G and Db that we get by walking the circle of fifths and comparing the Gb in Db major to the G in G major (and the F# in G major to the G in G major respectively). The point is that in any key that contains a tone called F#, the pitch of that tone is different from any tone called Gb in any other key.
Comment: It's not necessary to go to different keys to find intervals that no longer work; looking at a different chord in the same key can also have the same result.  The classic example for a major key is the sixth scale degree, which must be rather lower to serve as the just major third of a IV chord than where it needs to be to serve as the fifth of a ii or V/V chord.
Comment: @phoog, it's my understanding that chords are constructed from degrees of the scale, not by modulating the intervals from the root. So in JI the IV chord will contain different intervals than the I chord (as you note), but will still sound  correct in the context of the scale and tuning. If that's incorrect, please point me to a resource that discusses this since there's a lot of confusion in this area and it's better to stick to reputable references.
Comment: I do not know of a resource, but a few minutes with a calculator or spreadsheet will show that (assuming fixed pitches) if you have a single just third in your tuning, you will have an unusable fifth.  Looking at just the white keys in C major, you could accept a Pythagorean third in the F chord to save the fifth between D and A, but then you break the fifth between A and E. You could put the E in a Pythagorean third with C, but then you have a bad fifth between E and B.  If you raise the B, you have no more just thirds, so are left with Pythagorean tuning.
Answer: It is neither easy nor difficult to compose in JI, it is not a significant part of the history of western music, especially over the past 600± years. JI is based on the fundamental. Western music in developing tonality is based on sets of hierarchical relationships where 'scale degree' ^1 is more important than ^5, and harmonically, ^5 is more important than ^2, etc with ^2, ^6, ^3. Using JI for tonal harmony, while interesting, has no historical, or acoustic basis.
Comment: This is misleading.  While the general trend in Western music has been towards developing tunings that lend themselves to modulation and equality of intervals, this has been by way of compromising the acoustic basis, which is geometrical or just.  And this trend is fairly recent- until about five hundred years ago, there was no need felt to modulate.

Why Is Just Intonation Impractical?


Como recuperar valor de um inteiro e setar em um alertDialog

Question: Ao abrir o alertDialog o resultado fica como zero, segue o código
calcular.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String adulto = edit_adulto.getText().toString();
            String crianca = edit_crianca.getText().toString();

            dialog = new AlertDialog.Builder(MainActivity.this);
            dialog.setTitle("Resultado");
            dialog.setMessage("O valor é: " + resultadoA);
            dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            if (dia.isChecked()){

                if(!adulto.isEmpty()){
                    valorDigitadoA = Integer.parseInt(adulto);
                    resultadoA = valorDigitadoA * 15;
                    dialog.show();
                }
                if(!crianca.isEmpty()){
                    valorDigitadoC = Integer.parseInt(crianca);
                     resultadoC = (valorDigitadoC * 10);
                }
            }

Answer: Você deve usar o método setMessage dentro da condição logo após atribuir o valor desejado a sua variável. Veja como deve ficar:
if(!adulto.isEmpty()){
    valorDigitadoA = Integer.parseInt(adulto);
    resultadoA = valorDigitadoA * 15;

    // aqui será mostrado a mensagem no dialogo
    // com o valor atribuído a variável resultadoA
    dialog.setMessage("O valor é: " + resultadoA);
    dialog.show();
}

Comment: deu certinho amigo, obrigado pela ajuda!
Answer: Não aparece nada porque você está setando o texto do Dialog com a variável ResultadoA antes dela ter algum valor.


Windows Domain accounts gets locked without any failed logon events

Question: I have a domain account which keeps getting locked without any prior wrong password login attempts:
I.e (completely stripped off the details, just to give you an idea)
10:15:49 - logon successful
10:16:55 - logon failed (account locked)
There's something very odd here: I would expect at least one event between a successful logon and failed logon due to locked password. Where's the event that causes the lock with a failed password?
Other information:
-It's a MS RemoteApp system: there's a remoteapp system where people login via a web portal. The authentication happens during people logging into the web portal.
-There's no genius who's randomly locking accounts, even that should be in the logs, amirite?
Comment: Are failed logins being logged across all domain controllers?
Comment: There's only one domain controller.
Answer: Microsoft's account lockout tools might help you figure out what's going on.

There's no genius who's randomly locking accounts, even that should be
  in the logs, amirite?

Not necessarily.
Honestly, I kind of want to copy and paste Ryan Ries' answer here, so I'll link it instead.
My guess would be that someone has used their personal account for a service, but that's only a random guess.
Comment: I've used that tool too. It showed "0" failed attempts but the account was locked regardless. Go figure!


Using a specific network interface for a socket in windows

Question: Is there a reliable way in Windows, apart from changing the routing table, to force a newly created socket to use a specific network interface? I understand that bind() to the interface's IP address does not guarantee this.
Answer: (Ok second time lucky..)
FYI there's another question here perform connect() on specific network adapter along the same lines...
According to The Cable Guy

Windows XP and Windows Server® 2003
use the weak host model for sends and
receives for all IPv4 interfaces and
the strong host model for sends and
receives for all IPv6 interfaces. You
cannot configure this behavior. The
Next Generation TCP/IP stack in
Windows Vista and Windows Server 2008
supports strong host sends and
receives for both IPv4 and IPv6 by
default on all interfaces except the
Teredo tunneling interface for a
Teredo host-specific relay.

So to answer your question (properly, this time) in Windows XP and Windows Server 2003 IP4 no, but for IP6 yes. And for Windows Vista and Windows 2008 yes (except for certain circumstances).
Also from https://forums.codeguru.com/showthread.php?487139-Socket-binding-with-routing-table

On Windows, a call to bind() affects
card selection only incoming traffic,
not outgoing traffic. Thus, on a
client running in a multi-homed system
(i.e., more than one interface card),
it's the network stack that selects
the card to use, and it makes its
selection based solely on the
destination IP, which in turn is based
on the routing table. A call to bind()
will not affect the choice of the card
in any way.
It's got something to do with
something called a "Weak End System"
("Weak E/S") model. Vista changed to a
strong E/S model, so the issue might
not arise under Vista. But all prior
versions of Windows used the weak E/S
model.
With a weak E/S model, it's the
routing table that decides which card
is used for outgoing traffic in a
multihomed system.
See if these threads offer some
insight:
"Local socket binding on multihomed
host in Windows XP does not work" at
http://www.codeguru.com/forum/showthread.php?t=452337
"How to connect a port to a specified
Networkcard?" at
http://www.codeguru.com/forum/showthread.php?t=451117.
This thread mentions the
CreateIpForwardEntry() function, which
(I think) can be used to create an
entry in the routing table so that all
outgoing IP traffic with a specified
server is routed via a specified
adapter.
"Working with 2 Ethernet cards" at
http://www.codeguru.com/forum/showthread.php?t=448863
"Strange bind behavior on multihomed
system" at
http://www.codeguru.com/forum/showthread.php?t=452368

Hope that helps!
Comment: So, 11 years later, the best answer is still "Not possible"?
Comment: All of the CodeGuru links in this answer are broken
Comment: Thanks,
Unless I am missing something, neither answer is relevant, as SO_BINDTODEVICE is not relevant to windows.

I suspect your summary is correct though, even though I do not have the evidence.
Comment: Oops right you are! Updated my answer above with better info - sorry!
Comment: Note that the weak and strong host models do not affect how traffic sent from a socket is routed. I.e. the strong host model ensures that traffic leaving a network adapter uses that adapter's assigned IP address, but does not affect how the network stack in the host itself selects the outgoing adapter to actually use. This is actually explained in "The Cable Guy" link above, as well as on Wikipedia: https://en.wikipedia.org/wiki/Host_model
Comment: In certain protocols, such as with icmpv6 neighbor discovery, it is possible to send packets with the unspecified address (i.e. `::`) as the source. A router solicitation message for instance might have (dst `ff02::2` (link local all routers), and `::` as source). If one opened a raw IPv6 socket on windows and sent such a packet, would it go out on all interfaces? Is the implication in this case that there is no other way to restrict the output interface besides forcing the src to be the interface's link-local IP?
Comment: (Main (first) CodeGuru link fixed)
Comment: Look at the other answer, 10 years later it actually seems possible.
Answer: I'm not sure why you say bind is not working reliably. Granted I have not done exhaustive testing, but the following solution worked for me (Win10, Visual Studio 2019). I needed to send a broadcast message via a particular NIC, where multiple NICs might be present on a computer. In the snippet below, I want the broadcast message to go out on the NIC with IP of .202.106.
In summary:

create a socket
create a sockaddr_in address with the IP address of the NIC you want to send FROM
bind the socket to that FROM sockaddr_in
create another sockaddr_in with the IP of your broadcast address (255.255.255.255)
do a sendto, passing the socket created is step 1, and the sockaddr of the broadcast address.

`
static WSADATA     wsaData;

static int ServoSendPort = 8888;
static char ServoSendNetwork[] = "192.168.202.106";
static char ServoSendBroadcast[] = "192.168.255.255";

`
... < snip >
if ( WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR )
      return false;

// Make a UDP socket
SOCKET ServoSendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
int iOptVal = TRUE;
int iOptLen = sizeof(int);
int RetVal = setsockopt(ServoSendSocket, SOL_SOCKET, SO_BROADCAST, (char*)&iOptVal, iOptLen);

// Bind it to a particular interface
sockaddr_in ServoBindAddr={0};
ServoBindAddr.sin_family = AF_INET;
ServoBindAddr.sin_addr.s_addr = inet_addr( ServoSendNetwork ); // target NIC
ServoBindAddr.sin_port = htons( ServoSendPort );
int bindRetVal = bind( ServoSendSocket, (sockaddr*) &ServoBindAddr, sizeof(ServoBindAddr) );
if (bindRetVal == SOCKET_ERROR )
{
    int ErrorCode = WSAGetLastError();
    CString errMsg;
    errMsg.Format (  _T("rats!  bind() didn't work!  Error code %d\n"), ErrorCode );
    OutputDebugString( errMsg );
}

// now create the address to send to...
sockaddr_in ServoSendAddr={0};
ServoSendAddr.sin_family = AF_INET;
ServoSendAddr.sin_addr.s_addr = inet_addr( ServoSendBroadcast ); //
ServoSendAddr.sin_port = htons( ServoSendPort );

...
#define NUM_BYTES_SERVO_SEND 20
unsigned char sendBuf[NUM_BYTES_SERVO_SEND];
int BufLen = NUM_BYTES_SERVO_SEND;

ServoSocketStatus = sendto(ServoSendSocket, (char*)sendBuf, BufLen, 0, (SOCKADDR *) &ServoSendAddr, sizeof(ServoSendAddr));
if(ServoSocketStatus == SOCKET_ERROR)
{
    ServoUdpSendBytes = WSAGetLastError();
    CString message;
    message.Format(_T("Error transmitting UDP message to Servo Controller: %d."), ServoSocketStatus);
    OutputDebugString(message);
    return false;
 }

Comment: Thanks. I've asked this during 2010, at which time bind() definitely wasn't doing so reliably, glad to hear that's resolved now :)
Comment: Was looking for such a refresh of the answer. I wonder how things are supposed to be handled on stackoverflow for that.


Diff module not tracking fields that existed before module was installed

Question: I have a Drupal project in the final stages of development. It has quite a lot of content types and a lot of fields. I have recently enabled revisions and added the diff module (7.x-3.2). It isn't tracking changes on my existing fields. When I choose 'compare' it shows 'No visible changes' and the current revision area only shows the new fields.
If I add a new field diff starts working on it. If I remove a field and re-add it diff starts working on the new version of the field. Any idea why this is happening? Are there any ways I can get diff working on all my fields without removing an re-adding all of them?
I tried editing and saving a field without making any changes to it, but this did not make diff tracking start working on it. I have looked in the DB and both a field being tracked and a field that isn't being tracked have a revision_id.
I have tested in a sandbox server and the diff module works as expected. Therefore it must be a conflict or a bug that is being triggered by my install.
Answer: Did you read the README for the module and go through the module configuration? See CONFIGURATION section of the readme.

2) Field revisioning settings

   Global settings per field type can be found here:

   http://www.example.com/admin/config/content/diff/fields

   "Show field title" toggles field title visibility on the comparison page.

   "Markdown callback" is the callback used to render the field when viewing the
   page in the "Marked down" page view.

   "Line counter" is an optional. This shows the approximate line number where
   the change occurred. This is an approximate counter only.

   Other fields add additional settings here.

This Diff Issue Queue item describes a similar "No visible changes." problem encountered by another user.
From the issue it sounds like the diff comparison view, which is typically <code>"Standard comparision preview" settings == "Full content"</code> needs to be configured to show the fields you want, or be the correct view_mode for the content.
Comment: The link does decribe the same issue: I had disabled hidden all my fields in the default view.  So on the page admin/structure/types/manage/mynodetype I changed the 'standard comparison preview' from 'Full content' to 'Revision comparison'.

I then went to admin/structure/types/manage/mynodetype/display, opened the collapsed field 'custom display settings' and checked 'Revision comparison'. Then in the revision comparison view that was created I made sure the format for each field was no longer set to 'hidden'. Now the diff module is working as expected.


Minecraft - Bukkit Sockets

Question: I tried to get MOTD of the remote server, but I can't get colors. When MOTD is colored, the plugin isn't working.
I know why, but I don't know how to resolve it.
public PingServer(String host, int port) {
    this.host = host;
    this.port = port;

    try {
        socket.connect(new InetSocketAddress(host, port));
        OutputStream out = socket.getOutputStream();
        InputStream in = socket.getInputStream();
        out.write(0xFE);

        int b;
        StringBuffer str = new StringBuffer();
        while ((b = in.read()) != -1) {
            if (b != 0 && b > 16 && b != 255 && b != 23 && b != 24) {
                str.append((char) b);
            }
        }

        data = str.toString().split("§");
        data[0] = data[0].substring(1, data[0].length());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

According to the specification, the plugin will get response like this: MOTD§ONLINEPLAYERS§MAXPLAYERS, which should be split on § to get the different portions.  However, § is also used for chat messages, and I'm not sure how to differentiate between the two.  How can I work around this?
Comment: Please specify a few examples and how they should be decoded.
Comment: Are you using an old MC version?  The [ping](http://wiki.vg/Server_List_Ping) hasn't looked like that since 1.6.
Comment: No really. I'm using 1.8.8 and i can say this method is working well. Only colors... :( Do you have better idea?
Comment: Xan - OK, let's say Motd is §aLobby (Green title Lobby) and online player is 1 and max players are 50.
Result: §aLobby§1§50
So split isn't working now because MOTD isn't data[0] but data[1] and MOTD isn't colored but looking like that: aLobby
Comment: Oh, you're performing a legacy server list ping.  You shouldn't do that, as it's designed for legacy clients and missing a lot of information (probably including colors).  See [the "Current" section of this article](http://wiki.vg/Server_List_Ping#Current).  You don't need to split on `§` anymore, so the problem of embedded color codes won't exist anymore (it'll be properly stored in a JSON blob).
Comment: @Pokechu22 - Thank you! It working! You can write it as answer.
Answer: You're currently using the legacy server list ping, designed for beta 1.8 to 1.3.  That one is triggered via sending just FE to the server.  While current servers still support this ping, it's very old and has several flaws (including the one you found).
You should instead perform the current ping.  While this is slightly more complicated, you don't need to implement much of the protocol to actually perform it.
There's only one complicated portion of the protocol you need to know about: VarInts.  These are somewhat complicated because they take a varying number of bytes depending on the value.  And as such, you have a packet length that can be somewhat hard to calculate.
/** See http://wiki.vg/Protocol_version_numbers.  47 = 1.8.x */
private static final int PROTOCOL_VERSION_NUMBER = 47;
private static final int STATUS_PROTOCOL = 1;
private static final JsonParser PARSER = new JsonParser();

/** Pings a server, returning the MOTD */
public static String pingServer(String host, int port) {
    this.host = host;
    this.port = port;

    try {
        socket.connect(new InetSocketAddress(host, port));
        OutputStream out = socket.getOutputStream();
        InputStream in = socket.getInputStream();

        byte[] hostBytes = host.getBytes("UTF-8");
        int handshakeLength =
                varIntLength(0) + // Packet ID
                varIntLength(PROTOCOL_VERSION_NUMBER) + // Protocol version number
                varIntLength(hostBytes.length) + hostBytes.length + // Host
                2 + // Port
                varIntLength(STATUS_PROTOCOL);  // Next state

        writeVarInt(handshakeLength, out);
        writeVarInt(0, out);  // Handshake packet
        writeVarInt(PROTOCOL_VERSION_NUMBER, out);
        writeVarInt(hostBytes.length, out);
        out.write(hostBytes);
        out.write((port & 0xFF00) >> 8);
        out.write(port & 0xFF);
        writeVarInt(STATUS_PROTOCOL, out);

        writeVarInt(varIntLength(0));
        writeVarInt(0);  // Request packet (has no payload)

        int packetLength = readVarInt(in);
        int payloadLength = readVarInt(in);
        byte[] payloadBytes = new int[payloadLength];
        int readLength = in.read(payloadBytes);
        if (readLength < payloadLength) {
            throw new RuntimeException("Unexpected end of stream");
        }
        String payload = new String(payloadBytes, "UTF-8");

        // Now you need to parse the JSON; this is using GSON
        // See https://github.com/google/gson
        // and http://www.javadoc.io/doc/com.google.code.gson/gson/2.8.0
        JsonObject element = (JsonObject) PARSER.parse(payload);
        JsonElement description = element.get("description");
        // This is a naive implementation; it assumes a specific format for the description
        // rather than parsing the entire chat format.  But it works for the way the
        // notchian server impmlements the ping.
        String motd = ((JsonObject) description).get("text").getAsString();

        return motd;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

public static int varIntLength(int value) {
    int length = 0;
    do {
        // Note: >>> means that the sign bit is shifted with the rest of the number rather than being left alone
        value >>>= 7;
        length++;
    } while (value != 0);
}

public static void writeVarInt(int value, OutputStream out) {
    do {
        byte temp = (byte)(value & 0b01111111);
        // Note: >>> means that the sign bit is shifted with the rest of the number rather than being left alone
        value >>>= 7;
        if (value != 0) {
            temp |= 0b10000000;
        }
        out.write(temp);
    } while (value != 0);
}
public static int readVarInt(InputStream in) {
    int numRead = 0;
    int result = 0;
    int read;
    do {
        read = in.read();
        if (read < 0) {
            throw new RuntimeException("Unexpected end of stream");
        }
        int value = (read & 0b01111111);
        result |= (value << (7 * numRead));

        numRead++;
        if (numRead > 5) {
            throw new RuntimeException("VarInt is too big");
        }
    } while ((read & 0b10000000) != 0);

    return result;
}

The current ping does use JSON, which means you need to use GSON.  Also, this implementation makes some assumptions about the chat format; this implementation could break on custom servers that implement chat more completely, but it'll work for servers that embed § into the motd instead of using the more complete chat system (this includes the Notchian server implementation).

If you need to use the legacy ping, you can assume that the 2nd-to-last § marks the end of the MOTD (rather than the 1st §).  Something like this:
String legacyPingResult = str.toString();
String[] data = new String[3];
int splitPoint2 = legacyPingResult.lastIndexOf('§');
int splitPoint1 = legacyPingResult.lastIndexOf('§', splitPoint2 - 1);

data[0] = legacyPingResult.substring(0, splitPoint1);
data[1] = legacyPingResult.substring(splitPoint1 + 1, splitPoint2);
data[2] = legacyPingResult.substring(splitPoint2 + 1);

However, I still don't recommend using the legacy ping.

Minecraft - Bukkit Sockets


Send mail notification when node of given type gets created

Question: Use case: a small site where I want to warn all users by mail whenever a new content of a particular type is created. I thought I would try Rules+Actions to handle this.
I'm working on a vanilla Drupal 8 test site on my workstation, so there is just "Article" and "Basic Page".
I've installed the Rules module ok. I've looked at several videos explaining how this works in Drupal 7 and they looked reasonable straightforward. Now I'm trying to do something in D8 and finding it less than obvious.
Specifically, I've created the rule to fire when new content is created, and now I'm on a page editing Condition, where I want to specify that the node type is "Article". Using "Data selection" mode in the "Entity" field I select "node.type". This seems logical, but what on earth do I put in "Type"? No matter what I put I get a message something like this: "Data selector node.entity for context Entity is invalid. Unable to apply data selector 'entity' at 'entity' " - which is about as unexplicit as you can get.
Maybe I'm jumping the gun and Rules is not usable yet? Or maybe I've just not understood it at all...
But I would really appreciate if somebody could explain to me what seems quite straightforward in principle. How do I add a condition to my Rule that will cause the rule to fire only on a specific content type?
Comment: use https://www.drupal.org/project/business_rules, in project page there is a link to a youtube tutorial
Answer: Answering the "what do I put in the 'type' box?" question, the answer appears to be the same as for D7 - that is, the same status you'd pass to drupal_set_message().
This gives you options of:

status
warning
error

As to the state of D8 and specifically D8 rules, I share your pain - and it's nine months since you asked the question!
Answer: I don't know what the status of Rules was when this question was first asked, but the following is a complete example of how to use the "Node is of type" condition to check if a newly-created node is an article. I have had a similar rule working on my site for more than two years now - Rules has definitely been working and usable since then for things like this.
langcode: en
status: false
dependencies: {  }
id: new_article_created
label: 'New article created'
events:
  -
    event_name: 'rules_entity_insert:node'
description: 'Issue #2852342-16: Shows a system message when a new node of type ''article'' is created.'
tags: { }
config_version: '3'
expression:
  id: rules_rule
  uuid: f8e466d6-51d6-41ea-93f1-34436470f3c3
  conditions:
    id: rules_and
    uuid: 7776a869-e0c6-4499-b09e-da727722213e
    conditions:
      -
        id: rules_condition
        uuid: 6bf893f5-7bcf-420c-9a62-7e1cb9a884f6
        context_values:
          types:
            - article
        context_mapping:
          node: node
        context_processors:
          types:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_node_is_of_type
        negate: false
  actions:
    id: rules_action_set
    uuid: f0bcccfd-685f-4a74-a4fd-0d36b540037a
    actions:
      -
        id: rules_action
        uuid: ec599dbc-cb40-448b-b37b-129d956c2eb7
        context_values:
          message: 'New article created: {{ node.title }}'
          type: status
          repeat: false
        context_mapping: {  }
        context_processors:
          message:
            rules_tokens: {  }
          type:
            rules_tokens: {  }
          repeat:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_system_message


Strictly convex minimum and maximum

Question: Suppose that $a\lt b$ and $f:[a,b]\longrightarrow\mathbb{R}$.
We say that f is strictly convex on $[a,b]$ if, for each $a,y\in[a,b]$ with $x\neq y$, $$f(0.5x+0.5y) \lt 0.5f(x)+0.5f(y)$$.
If $f$ is continuous and strictly convex (by the above definition) on $[a,b]$ then I want to prove that $f$ attains a unique minimum in $[a,b]$ and a maximum value at either $a,b $ or both.
This is what I have so far:
The existence of both follows from the min-max theorem as $f$ is continuous on a closed interval.
The minimum was straight forward, I did a proof by contradiction, assuming two minima and then showing, by the definition of strictly convex, that we got another point $x$, where $f(x) \lt f(c)$ (when c was one of our minima).
With the maxima I couldn't get anywhere. I tried assuming a maxima on $(a,b)$, again trying for contradiction but I had no luck. Any help would be great!
Answer: Suppose $c \in (a,b)$ is the global maximum over $[a,b]$.
Let $d= \min(c-a, b-c)$, then $c-d,c+d \in [a,b]$.
Let $x=c-d$ and $y=c+d$, then we can conclude that
$$f(c)< 0.5f(x)+0.5f(y)$$
Try to argue that $f(x)>f(c)$ or $f(y)>f(c)$ to get a contradiction.
Comment: Thanks a lot, this makes sense!

Strictly convex minimum and maximum


Clarifications on varnish cache

Question: When a page is cached in varnish, internally does it store the page on disk or memory?
What if a single server cannot store all the cached pages, does it have clustering or do you then choose which varnish server to cache? i.e. it is done at the application level?
Answer: by default it stores it on disk but lets the OS decide to keep it in memory or not. There is also the malloc option which says always store in RAM and persist option which means keep the cache on disk and save even on a restart
https://www.varnish-cache.org/docs/3.0/reference/varnishd.html#storage-types
There is no clustering but you can specify how big you want your cache to be.
Comment: so how would a site like facebook use varnish when there is no clustering?  i.e. it all can't fit on a single server.  i guess something like haproxy is used to hash the request and send it to the correct varnish box?
Comment: so you what if your cache can't fit on a single server? how do you shard, based on?
Comment: facebook isn't 1 giant app.. it is many apps all making up a big one. So all requests are going through many caching layers. I know they use varnish.. just not sure to what extent.

Clarifications on varnish cache


Como criar um "novo arquivo" .txt no java?

Question: Minhas dúvidas são: esse código está correto?
como faço para limpe a tela e abre o novo arquivo criado?
menuNovo.setOnAction((ActionEvent e) -> {
            Stage janela = (Stage) areaTexto.getScene().getWindow();
            String nome = JOptionPane.showInputDialog("Digite o nome do arquivo");
            File arquivo = new File(nome + ".txt");
        });

Answer: Essa linha é desnecessária:
Stage janela = (Stage) areaTexto.getScene().getWindow();

janela não está sendo utilizado em nenhum lugar dentro do listener do evento. Lembrando que eventos podem ser mapeados dentro do próprio arquivo .fxml e referenciados no código com a anotação @FXML.
Não misture swing e JavaFX. Ainda que não haja problemas — por enquanto — o recomendável é manter cada coisa no seu quadrado. Todos os componentes presentes no swing, podem ser feitos com JavaFX sem a necessidade de misturá-los. JOptionPane.showInputDialog() pode ser substituído por um TextInputDialog — ainda que seja um pouco mais verboso, vide código de exemplo abaixo.
Pode também utilizar as classes do pacote java.nio.file.* para manipular arquivos.
menuNovo.setOnAction((ActionEvent e) -> {

   // Cria o dialog.
   TextInputDialog dialog = new TextInputDialog(null);
   dialog.setTitle("Digite no nome do arquivo");
   dialog.setHeaderText("Digite o nome do arquivo.");;

   // Exibe o dialog e espera pelo valor digitado.
   Optional<String> value = dialog.showAndWait();

   // Se algo for digitado no dialog, cria o arquivo com o nome especificado.
   if (value.isPresent()) {
      try {
         Path file = Paths.get(value.get().concat(".txt"));
         Files.createFile(file);
      } catch (IOException ex) {
         // Tratar exceção no caso de falha na criação do arquivo.
      }
   }
});

Se precisar escrever no arquivo, já foi respondido aqui.


How to do a regression which includes reciprocals?

Question: I'm trying to find an interpolating formula for a set of coefficients (I have $80$ at the moment).
I tried first to find an interpolating polynomial, but that was not useful: using the first $40$ coefficients only and extrapolate that formula to a guess for the other $40$ coefficients leads to catastrophic error.
So I tried another path: first find a linear expression which interpolates as smooth as possible (simple linear regression). Then it seems, that the reciprocals of the residuals might be best approximated by a next step of linear regression - and after some manual guesses it seems, that it is again most appropriate to use again the reciprocals of the new residuals with a linear or a quadratic curve - and possibly so on.
The idea for a regression formula were thus the following with $2$ pairs of parameters where the coefficients are indicated by $y_k$ ,$N=40$ and $k=1..N$ :
$$ \sum_{k=1}^N \left( {1 \over y_k -(a_0+a_1 k) } - (b_0+b_1 k) \right)^2 \overset{!}{=} min $$
Possibly this must then be continued by a next step, where again the reciprocals of the new residuals must be approximated by a quadratic regression, so in principle I look for some algorithm which will be mechanically extensible, but that's only the next step. So just for a start:

Q: What would be the formula to determine the four parameters?

See the requested data in a separate "answer" to keep the question better readable.
[update] P.s. : I've had similar problems casually in earlier problems (from my numbertheory fiddlings), and got in such cases stuck with some manual optimizations - so the principle of such a regression would serve me enough, please don't put too much effort in some extreme finetuning of the parameters on base of that 80 datapoints.
[update2] A bit more background to avoid misconceptions and to avoid frustration to someone willing to help. The data stem from a problem in number theory (see here in MSE) where I found a sequence of (infinitely many) points which seem to approximate to a linear or near linear decrease (linear with the index).
The problem is the following. Begin with the complex number $z_0=1$. Iterate $z_{k+1}=î ^ z_k$ (where $î$ is the imaginary unit) which process converges to a fixpoint $t$. Take the (euclidean) distance $d$ of each iterate $d_k = |z_k - t|$ . The given data $y_k$ are the $\log()$ of the $d_k$.
There is very likely no simpler function for that values available, but a functional approximation to the $y_k$ seems to be primarily linear with some unknown, diminuishing secondary distortion, again systematic.
A good approximation is enough for my purposes, but must be robust for extrapolation to infinitely many datapoints. I need not only one "practical" approximation but a method because the same problem with improving approximation to linearity occurs as well with the angular value $ \arg(z_k-t)$ for which I want then apply the same procedure.
Trying to find a working model using the ansatz of regression brought me to the above formula with four parameters (for a start) which I cannot expand/resolve for a formal solution.
Comment: Can we see your data ?
Comment: @Yves : I've put the data into an answer-box to not to clutter the question too much.
Comment: Not sure what you are trying to do. After initial oscillations, the fit to a line gets better and better as the point index increases. Why do you split in two subsets ?
Comment: @Yves: the splitting is done to have some sanity check of the procedure. For how many current data-points I'll do any optimizaton, there will be infinitely many more for which that optimization must be sensical. The problem is that an estimation will always face the problem that I have to extrapolate to hiher indexes. So this splitting shall give some indication, whether the found optimization can be meaningful at all. Consider the polynomial interpolation. I did it with first forty points and got exact fit. But extrapolated to further points showed catastrophic error, so this splitting...
Comment: ... was an instrument to uncover the inappropriateness of the polynomial interpolation at all. I think the same applies to any method - even with this regression-model.
Comment: Polynomial interpolation is indeed unusable above, say, ten points. But regression behaves very well, except in the case of outliers. In your case I see a nice linear law and I wonder why you want to complexify the model. The initial points are a little dangerous because of the oscillations, which aren't modelled, but they decay steadily. I would just ignore the first 20 or so. I still can't understand your intent.
Comment: @Yves - well actually I *used* that linear interpolation as rough approximation (as well as a more sophisticated formula, but that's complete different path, see the new link in my updated answer). I just saw *room for improvement* and tried to make sense of the above regression-model. My problem is simply to derive the solution for the parameters for a regression, where the data-to-be-fit (resp. the intended residuals) are in the *denominator* of the regression-formula which is quite unusual for me. I thought there might be some (simple) canonical answer for such a question.
Comment: From what I have seen, the residuals are oscillating around a straight line and adding non-oscillating terms won't help. But I can be wrong.
Answer: Based on your initial question and using the values you give, I considered the function  $$F(a_0,a_1,b_0,b_1)=\sum_{k=1}^{80} \left( {1 \over y_k -(a_0+a_1 k) } - (b_0+b_1 k) \right)^2 $$ and I just minimized it numerically.
The minimum is found for the following parameters $$a_0=36.9437\quad a_1=-0.127637$$ $$b_0=-0.0268729\quad b_1=-9.57943 \times 10^{-6}$$ for which $F_{opt}=1.06724\times 10^{-7}$
Comment: Hi Claude! Very nice - I had given up because of an insufficient test-environment for simultanously adapt four parameters... I'll see what this gives to me, thanks so far!
Answer: Data which I'm working on. I use $80$ values but put it here in two portions a $40$ (vertically). I'm getting an approximation-formula from the left block of forty values and check the appropriateness by application to the full dataset. The left column of each block is the index which begins at $1$ to allow formulae with reciprocals. The data stem from a formula by which I can successively get infinitely
more values (but practically limited to some $100$ or $200$ data-points)

data in csv-format:   file

data in mathjax-format:

$$\small \begin{array} {rl|rl}
 1 & -0.404219547134 & 41 & -4.96369610919 \\
 2 & -0.254635150576 & 42 & -5.08346228643 \\
 3 & -0.848826900252 & 43 & -5.19387328015 \\
 4 & -0.672497295471 & 44 & -5.30980799271 \\
 5 & -0.782648581294 & 45 & -5.42691064949 \\
 6 & -1.09661390701 & 46 & -5.53829673204 \\
 7 & -0.941305565047 & 47 & -5.65523782695 \\
 8 & -1.20932963584 & 48 & -5.77042934573 \\
 9 & -1.36432295221 & 49 & -5.88318317015 \\
 10 & -1.28358177556 & 50 & -6.00009058654 \\
 11 & -1.58603096933 & 51 & -6.11423257056 \\
 12 & -1.65776438414 & 52 & -6.22820436618 \\
 13 & -1.67153909479 & 53 & -6.34456590114 \\
 14 & -1.93014001210 & 54 & -6.45835690750 \\
 15 & -1.96844248450 & 55 & -6.57316075367 \\
 16 & -2.06003832171 & 56 & -6.68885932414 \\
 17 & -2.25865650761 & 57 & -6.80273947156 \\
 18 & -2.29610558688 & 58 & -6.91796901573 \\
 19 & -2.43438066384 & 59 & -7.03311492793 \\
 20 & -2.58368257882 & 60 & -7.14728282076 \\
 21 & -2.63902124916 & 61 & -7.26262536683 \\
 22 & -2.79434601545 & 62 & -7.37741464273 \\
 23 & -2.91134973187 & 63 & -7.49189688720 \\
 24 & -2.99089127097 & 64 & -7.60716668365 \\
 25 & -3.14368853097 & 65 & -7.72178845853 \\
 26 & -3.24410305971 & 66 & -7.83651835597 \\
 27 & -3.34517482343 & 67 & -7.95164075044 \\
 28 & -3.48674797680 & 68 & -8.06623261683 \\
 29 & -3.58231400466 & 69 & -8.18111355575 \\
 30 & -3.69791558146 & 70 & -8.29608865051 \\
 31 & -3.82709089874 & 71 & -8.41072732188 \\
 32 & -3.92498019330 & 72 & -8.52567229447 \\
 33 & -4.04770179897 & 73 & -8.64053766338 \\
 34 & -4.16709403679 & 74 & -8.75524974887 \\
 35 & -4.27042930487 & 75 & -8.87019875417 \\
 36 & -4.39467132300 & 76 & -8.98500120459 \\
 37 & -4.50802943507 & 77 & -9.09978136831 \\
 38 & -4.61704538184 & 78 & -9.21470325795 \\
 39 & -4.73962423078 & 79 & -9.32948231359 \\
 40 & -4.85032671658 & 80 & -9.44431053345
 \end{array}$$

data in textformat:

data
<code>   1  -0.404219547134  41  -4.96369610919
   2  -0.254635150576  42  -5.08346228643
   3  -0.848826900252  43  -5.19387328015
   4  -0.672497295471  44  -5.30980799271
   5  -0.782648581294  45  -5.42691064949
   6   -1.09661390701  46  -5.53829673204
   7  -0.941305565047  47  -5.65523782695
   8   -1.20932963584  48  -5.77042934573
   9   -1.36432295221  49  -5.88318317015
  10   -1.28358177556  50  -6.00009058654
  11   -1.58603096933  51  -6.11423257056
  12   -1.65776438414  52  -6.22820436618
  13   -1.67153909479  53  -6.34456590114
  14   -1.93014001210  54  -6.45835690750
  15   -1.96844248450  55  -6.57316075367
  16   -2.06003832171  56  -6.68885932414
  17   -2.25865650761  57  -6.80273947156
  18   -2.29610558688  58  -6.91796901573
  19   -2.43438066384  59  -7.03311492793
  20   -2.58368257882  60  -7.14728282076
  21   -2.63902124916  61  -7.26262536683
  22   -2.79434601545  62  -7.37741464273
  23   -2.91134973187  63  -7.49189688720
  24   -2.99089127097  64  -7.60716668365
  25   -3.14368853097  65  -7.72178845853
  26   -3.24410305971  66  -7.83651835597
  27   -3.34517482343  67  -7.95164075044
  28   -3.48674797680  68  -8.06623261683
  29   -3.58231400466  69  -8.18111355575
  30   -3.69791558146  70  -8.29608865051
  31   -3.82709089874  71  -8.41072732188
  32   -3.92498019330  72  -8.52567229447
  33   -4.04770179897  73  -8.64053766338
  34   -4.16709403679  74  -8.75524974887
  35   -4.27042930487  75  -8.87019875417
  36   -4.39467132300  76  -8.98500120459
  37   -4.50802943507  77  -9.09978136831
  38   -4.61704538184  78  -9.21470325795
  39   -4.73962423078  79  -9.32948231359
  40   -4.85032671658  80  -9.44431053345
</code>
Answer: If I well understand the question, you have the data $(x_k\:,\:y_k)$ where $k=1$ to $k=n$ ( in your example $n=80$ and $x_k=k$ ).
As the problem is settled, this is not exactly the fitting of a function to the data but in fact the fitting of an equation to the data, which is slightly different. The equation is :
$$\frac{1}{y-(a_0+a_1x)} - (b_0+b_1x)=0$$
The goal is to find approximates for $a_0\:,\:a_1\:,\:b_0\:,\:b_1$ so that the equation be at best satisfied.
$$ \left(y-(a_0+a_1x)\right)(b_0+b_1x)-1=0$$
$$b_0y+b_1xy-(a_1b_0+a_0b_1)x-a_1b_1x^2=1+a_0b_0$$
Let : $\quad C_1=\frac{b_0}{1+a_0b_0}\quad;\quad C_2=\frac{b_1}{1+a_0b_0}\quad;\quad C_3=-\frac{a_1b_0+a_0b_1}{1+a_0b_0}\quad;\quad C_4=-\frac{a_1b_1}{1+a_0b_0}$
Then, compute for $k=1$ to $k=n$ : $\quad p_k=x_ky_k \quad \text{and}\quad q_k=x_k^2$
The regression with linear mean square fitting of :
$$C_1y_k+C_2p_k+C_3x_k+C_4q_k\simeq1$$
will lead to $\:C_1\:,\:\:C_2\:,\:\:C_3\:,\:\:C_4\:$. Then, with the four relationships with $\:a_0\:,\:\:a_1\:,\:\:b_0\:,\:\:b_1\:$ one can compute the approximates of those four parameters.

I didn't test this method with your data because a simple linear regression seems convenient and leads to a very good fitting , or have I missed something ? :
Comment: Hmm, the rationale of the "regression" is the minimization of the error of prognosis in the sense of the least (sum-of) squares of the residuals. Now I'm missing the "squares" and the "sum" and the "minimum" in your first equation where you equal the lhs to zero. Speaking of "minimization" the *derivative* of a function should become zero (and the second derivative should become positive), not the function itself. Did I misread something in your ansatz?
Comment: Thre is no derivative at all in this method. As I said, it is not the usual mean square fitting in the sense of fitting a curve to data : http://mathworld.wolfram.com/LeastSquaresFitting.html . It is the fitting of an equation (wich is in fact the inplicit expression of the equation of the curve) : Section 5, page 10 in : https://fr.scribd.com/doc/14819165/Regressions-coniques-quadriques-circulaire-spherique .
Comment: To clearify this point, see the addidion to my first answer. But, of course, if it is strictly required the least squares with the common definition of the residuals, you have to use a non-linear method , for example : http://mathworld.wolfram.com/NonlinearLeastSquaresFitting.html
Comment: I added a link to a *.csv-file in my answer which contains the sample of data
Comment: I think now, that a simple answer is not possible since it is a non-linear regression-problem and I've to finetune any final approximation manually. So I just want to say thank you very much for all your help!
Comment: With the new link I got the sample of data. See the addition to my previous answer.
Comment: Step 1: Yes, I've done the same regression and got the same/a similar result. Step 2: But after that I looked at the residuals and noticed, that they have a trend to become absolutely smaller. So I considered to do a further improvement to find a characteristic of that. Looked at the residuals and at their reciprocals - observing/guessing that there is another linear trend. Thus the residuals of Step 1(as of your finding)  are in the denominator of my formula and I tried -as a higher order approximation- to get something useful by removing that trend. That's the reason for my complete formula.
Comment: OK. But looking at the magnitude of scatter on the left side of the curve, on my pinion, such an expected improuvement is questionable . Anyways, you are the sole judge.