Harmonic series: Difference between revisions

J draft
m (Clarified comment and the name of the harmonic_series variable)
(J draft)
Line 758:
Term 4550 is the first above 9
Term 12367 is the first above 10</pre>
 
=={{Header|J}}==
To calculate a specific value in the harmonic series, we might define:
<syntaxhighlight lang=J>Hn=: {{ +/ %1+i.y }}"0</syntaxhighlight>
 
Inspecting the first 20 values from Hn, we see:
<syntaxhighlight lang=J> Hn i.4 5
0 1 1.5 1.83333 2.08333
2.28333 2.45 2.59286 2.71786 2.82897
2.92897 3.01988 3.10321 3.18013 3.25156
3.31823 3.38073 3.43955 3.49511 3.54774
</syntaxhighlight>
 
However, this is inefficient -- we're regenerating the sequence each time just to add one more term. So, instead, we should move that <code>i.</code> inside our harmonic series generator:
 
<syntaxhighlight lang=J>Hni=: {{ 0,+/\ %1+i.y}}</syntaxhighlight>
 
Note that we've added an explicit 0 here -- that's both for compatibility with <code>Hn</code> and to ensure that the Hn value at index 1 has the value 1. (We're using a running sum here, which omits the empty case, but that empty case was relevant for us...)
 
Anyways:
<syntaxhighlight lang=J> 4 5$Hni 20
0 1 1.5 1.83333 2.08333
2.28333 2.45 2.59286 2.71786 2.82897
2.92897 3.01988 3.10321 3.18013 3.25156
3.31823 3.38073 3.43955 3.49511 3.54774</syntaxhighlight>
 
Inspecting values from the series, we see that 1e5 terms will get us into numbers larger than 12:
 
<syntaxhighlight lang=J> Hn 1e5
12.0901</syntaxhighlight>
 
So, we can show the index values of the first harmonic numbers which match or exceed integer values:
<syntaxhighlight lang=J> (Hni 1e5) (] ,. I. ,. I. { [) i.13
0 0 0
1 1 1
2 4 2.08333
3 11 3.01988
4 31 4.02725
5 83 5.00207
6 227 6.00437
7 616 7.00127
8 1674 8.00049
9 4550 9.00021
10 12367 10
11 33617 11
12 91380 12</syntaxhighlight>
 
Of course, the later values are not precise integers -- but their fractional part is not significant for J's default display precision:
 
<syntaxhighlight lang=J> (Hn 91380)-12
3.05167e_6</syntaxhighlight>
 
 
 
=={{header|jq}}==
Line 833 ⟶ 886:
integer = 10 -> n = 12367 -> harmonic number = 10.000043 (to 6dp)
</pre>
 
 
=={{header|Julia}}==
6,951

edits