Hickerson series of almost integers: Difference between revisions

m
syntax highlighting fixup automation
m (Updated description and link for Fōrmulæ solution)
m (syntax highlighting fixup automation)
Line 21:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Ada.Numerics.Generic_Elementary_Functions;
 
Line 82:
end;
end loop;
end Almost_Integers;</langsyntaxhighlight>
 
{{out}}
Line 107:
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
<langsyntaxhighlight lang="algol68"># determine whether the first few Hickerson numbers really are "near integers" #
# The Hickerson number n is defined by: h(n) = n! / ( 2 * ( (ln 2)^(n+1) ) ) #
# so: h(1) = 1 / ( 2 * ( ( ln 2 ) ^ 2 ) #
Line 143:
)
)
OD</langsyntaxhighlight>
{{out}}
<pre>
Line 167:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -M -f HICKERSON_SERIES_OF_ALMOST_INTEGERS.AWK
# using GNU Awk 4.1.0, API: 1.0 (GNU MPFR 3.1.2, GNU MP 5.1.2)
Line 186:
return(out)
}
</syntaxhighlight>
</lang>
<p>Output:</p>
<pre>
Line 218:
and a decimal part (using a string operation) before outputting.
<langsyntaxhighlight lang="bracmat">( 0:?n
& 1:?fac
& whl
Line 245:
)
)
);</langsyntaxhighlight>
{{out}}
<pre>h(1) = 1.041 is an almost-integer.
Line 267:
=={{header|C}}==
{{libheader|MPFR}}
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <mpfr.h>
 
Line 295:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 319:
=={{header|C++}}==
{{libheader|Boost|1.53 or later}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <iomanip>
#include <boost/multiprecision/cpp_dec_float.hpp>
Line 337:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 362:
In order to get enough precision, the natural logarithm of 2 had to be entered manually; the BigDecimal implementation does not have a high-precision logarithm function.
 
<langsyntaxhighlight lang="clojure">(defn hickerson
"Hickerson number, calculated with BigDecimals and manually-entered high-precision value for ln(2)."
[n]
Line 381:
(if (almost-integer? h)
"almost integer"
"NOT almost integer")))</langsyntaxhighlight>
{{out}}
<pre>1 1.04068 almost integer
Line 403:
=={{header|COBOL}}==
{{works with|GNU Cobol|2.0}}
<langsyntaxhighlight lang="cobol"> >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. hickerson-series.
Line 431:
END-PERFORM
.
END PROGRAM hickerson-series.</langsyntaxhighlight>
 
{{out}}
Line 457:
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">require "big"
LN2 = Math.log(2).to_big_f
Line 478:
puts "n:%3i h: %s\t%s" % [n, h, str]
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 502:
=={{header|D}}==
The D <code>real</code> type has enough precision for this task.
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.algorithm, std.mathspecial;
 
Line 511:
tenths.among!(0, 9) ? "" : "NOT ");
}
}</langsyntaxhighlight>
<pre>H( 1)= 1.04 is nearly integer.
H( 2)= 3.00 is nearly integer.
Line 531:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting kernel math math.factorials math.functions
math.ranges sequences ;
IN: rosetta-code.hickerson
Line 548:
] each ;
 
MAIN: hickerson-demo</langsyntaxhighlight>
{{out}}
<pre>
Line 574:
{{works with|4tH v3.64.0}}
4tH has two different floating point libraries. This version works with both of them.
<langsyntaxhighlight lang="forth">[UNDEFINED] ANS [IF]
include lib/fp1.4th \ Zen float version
include lib/zenfprox.4th \ for F~
Line 601:
;
 
first17</langsyntaxhighlight>
{{out}}
<pre>
Line 624:
 
=={{header|Fortran}}==
<langsyntaxhighlight lang="fortran">program hickerson
implicit none
integer, parameter :: q = selected_real_kind(30)
Line 646:
end do
1 format('h(',I2,') = ',F23.3,' is',A,' an almost-integer')
end program</langsyntaxhighlight>
 
{{out}}
Line 672:
=={{header|FreeBASIC}}==
{{libheader|GMP}}
<langsyntaxhighlight lang="freebasic">' version 08-10-2016
' compile with: fbc -s gui
 
Line 757:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>h(1) = 1.04068 is a almost integer
Line 809:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 831:
i, &w, d[1:], d[2] == '0' || d[2] == '9')
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 854:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Number.CReal -- from numbers
 
import qualified Data.Number.CReal as C
Line 874:
 
 
</syntaxhighlight>
</lang>
{{out}}
<pre style="font-size:80%">
Line 904:
Definitions:
 
<langsyntaxhighlight Jlang="j">ln2=: [: +/ 1 % [: (*2x&^) 1+i.
h=: ! % 2*(ln2 99)^>:</langsyntaxhighlight>
 
Implementation (1 in initial column indicates an almost integer, results displayed to 3 digits after the decimal point):
 
<langsyntaxhighlight Jlang="j"> 1 23j3": (h ,.~ 0 9 e.~ 10 <.@* 1 | h) x:1+i.17
1 1.041
1 3.003
Line 926:
1 230283190977853.037
0 5315654681981354.513
0 130370767029135900.458</langsyntaxhighlight>
 
In other words, multiply the fractional part of h by ten, find the largest integer not greater than this result, and check if it's in the set {0,9}. Then format the result of h along with this set membership result.
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.math.*;
 
public class Hickerson {
Line 957:
return c.toString().matches("0|9");
}
}</langsyntaxhighlight>
 
<pre> 1 is almost integer: true
Line 980:
{{works with|jq|1.4}}
jq currently uses IEEE 754 64-bit numbers, and therefore the built-in arithmetic functions lack adequate precision to solve the task completely. In the following, therefore, we include a check for adequate precision.
<langsyntaxhighlight lang="jq">def hickerson:
. as $n
| (2|log) as $log2
Line 1,004:
end
else "insufficient precision for hickerson(\($i))"
end</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -M -r -n -f Hickerson_series.jq
hickerson(1) is 1.0406844905028039 -- almost an integer
hickerson(2) is 3.0027807071569055 -- almost an integer
Line 1,023:
hickerson(15) is 230283190977853.06 -- almost an integer
insufficient precision for hickerson(16)
insufficient precision for hickerson(17)</langsyntaxhighlight>
 
=={{header|Julia}}==
This solution implements its Hickerson Series function as a closure. It explores the effects of datatype precision, implementing a rather conservative "guard number" scheme to identify when the results may have inadequate precision. One can not be confident of the 64-bit floating point results beyond <tt>n=13</tt>, but the 256-bit precision floating point results are easily precise enough for the entire calculation to <tt>n=17</tt>. (A slight variant of this calculation, not shown here, indicates that these extended precision numbers are adequate to <tt>n=50</tt>.)
<syntaxhighlight lang="julia">
<lang Julia>
function makehickerson{T<:Real}(x::T)
n = 0
Line 1,077:
a = log(2.0)
reporthickerson(a, 17)
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,292:
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="kotlin">// version 1.1.4
 
import java.math.BigDecimal
Line 1,314:
fun main(args: Array<String>) {
for (n in 1..17) println("${"%2d".format(n)} is almost integer: ${Hickerson.almostInteger(n)}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,338:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">h[n_] = n!/(2 (Log[2])^(n + 1));
firstdecimal[x_] := Floor[10 x] - 10 Floor[x];
almostIntegerQ[x_] := firstdecimal[x] == 0 || firstdecimal[x] == 9;
Table[{i, AccountingForm[N[h[i], 50], {Infinity, 5}], almostIntegerQ[N[h[i], 50]]}, {i, 1, 17}] // TableForm</langsyntaxhighlight>
{{out}}
<pre>1 1.04068 True
Line 1,363:
=={{header|ML}}==
==={{header|mLite}}===
<langsyntaxhighlight lang="ocaml">local
fun log (n, k, last = sum, sum) = sum
| (n, k, last, sum) = log (n, k + 1, sum, sum + ( 1 / (k * n ^ k)))
Line 1,379:
;
foreach show ` iota 17;
</syntaxhighlight>
</lang>
Output
<pre>(1, 1.04068449050280389893479080186749587, true)
Line 1,405:
For big values, it is not possible to keep enough precision while converting a rational to a float, so we compute only the fractional part of h(n), which is sufficient to decide whether the number if nearly an integer or not.
 
<langsyntaxhighlight Nimlang="nim">import strformat
import bignum
 
Line 1,430:
let s = if int(10 * f) in {0, 9}: "" else: "not "
echo &"Fractional part of h({i}) is {f:.5f}..., so h({i}) is {s}nearly an integer."
if i == 17: break</langsyntaxhighlight>
 
{{out}}
Line 1,452:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">h(n)=n!/2/log(2)^(n+1)
almost(x)=abs(x-round(x))<.1
select(n->almost(h(n)),[1..17])
</syntaxhighlight>
</lang>
{{out}}
<pre>%1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]</pre>
Line 1,467:
calculate the inverse of the natural log of 2, and then compute a running value of h.
 
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use Math::BigFloat;
Line 1,481:
$n, $s, ($s =~ /\.[09]/ ? "" : " NOT");
}
</syntaxhighlight>
</lang>
{{out}}
<pre>h( 1) = 1.041 is almost an integer.
Line 1,502:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">javascript_semantics</span> <span style="color: #000080;font-style:italic;">-- (no mpfr_log() for pwa/p2js)</span>
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.0"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (mpfr_set_default_prec[ision] renamed)</span>
Line 1,518:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%2d:%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n10</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,542:
=={{header|PicoLisp}}==
PicoLisp does not have floating point, but does have library functions to make fixed-point math easier. I use a scale factor of 25 to ensure that there is enough precision.
<syntaxhighlight lang="picolisp">
<lang PicoLisp>
(load "@lib/misc.l")
 
Line 1,579:
(prinl "h(" (align 2 I) ") = " (fmt4 H))))
(bye)
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,603:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">Hickerson: procedure options (main); /* 12 January 2014 */
declare s float (18), (i, n) fixed binary;
declare is fixed decimal (30);
Line 1,624:
end;
 
end Hickerson;</langsyntaxhighlight>
{{out}}
<pre>
Line 1,645:
</pre>
Using extended precision available by software:
<langsyntaxhighlight lang="pli">
do n = 1 to 18;
s = divide( float(0.5), float(0.693147180559945309417232121458) );
Line 1,662:
put edit (' is not a near integer') (A);
end;
</syntaxhighlight>
</lang>
{{out}} Results:
<pre>
Line 1,688:
This uses Pythons [http://docs.python.org/2/library/decimal.html decimal module] of fixed precision decimal floating point calculations.
 
<langsyntaxhighlight lang="python">from decimal import Decimal
import math
 
Line 1,705:
if 'E' not in norm and ('.0' in norm or '.9' in norm)
else ' NOT nearly integer!')
print('n:%2i h:%s%s' % (n, norm, almostinteger))</langsyntaxhighlight>
 
{{out}}
Line 1,731:
=={{header|Racket}}==
{{trans|Python}}
<langsyntaxhighlight Racketlang="racket">#lang racket
(require math/bigfloat)
 
Line 1,749:
(~r n #:min-width 2)
(bigfloat->string hickerson-n)
almost-integer))</langsyntaxhighlight>
{{out}}
<pre> 0: 0.7213475204444817036799623405009460687136 is not Nearly integer!
Line 1,775:
We'll use [http://doc.raku.org/type/FatRat FatRat] values, and a series for an [http://mathworld.wolfram.com/NaturalLogarithmof2.html approximation of ln(2)].
 
<syntaxhighlight lang="raku" perl6line>constant ln2 = [+] (1/2.FatRat, */2 ... *) Z/ 1 .. 100;
constant h = [\*] 1/2, |(1..*) X/ ln2;
 
Line 1,783:
for h[1..17] {
ok m/'.'<[09]>/, .round(0.001)
}</langsyntaxhighlight>
{{out}}
<pre>ok 1 - 1.041
Line 1,811:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 04.01.2014 Walter Pachl - using a rather aged ln function of mine
* with probably unreasonably high precision
Line 1,899:
fact=fact*i
End
Return fact</langsyntaxhighlight>
{{out}}
<pre> 1 1.0406844905 almost an integer
Line 1,925:
 
This version supports up to &nbsp; '''507''' &nbsp; decimal digits.
<langsyntaxhighlight lang="rexx">/*REXX program to calculate and show the Hickerson series (are near integer). */
numeric digits length(ln2())-length(.) /*be able to calculate big factorials. */
parse arg N . /*get optional number of values to use.*/
Line 1,944:
|| 3501153644979552391204751726815749320651555247341395258829504530070953263666426541042391578149520437404,
|| 3038550080194417064167151864471283996817178454695702627163106454615025720740248163777338963855069526066,
|| 83411372738737229289564935470257626520988596932019650585547647033067936544325476327449512504060694381470</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 197 </tt>}}
<pre style="height:91ex">
Line 2,148:
===version 3===
This REXX version takes advantage that the Hickerson series are computed in order, so that the factorials need not be (re-)computed from scratch.
<langsyntaxhighlight lang="rexx">/*REXX program to calculate and show the Hickerson series (are near integer). */
numeric digits length(ln2())-length(.) /*be able to calculate big factorials. */
parse arg N . /*get optional number of values to use.*/
Line 2,166:
|| 3501153644979552391204751726815749320651555247341395258829504530070953263666426541042391578149520437404,
|| 3038550080194417064167151864471283996817178454695702627163106454615025720740248163777338963855069526066,
|| 83411372738737229289564935470257626520988596932019650585547647033067936544325476327449512504060694381470</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 2<sup>nd</sup> REXX version.}}<br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
n = 12
hick = 0
Line 2,195:
else return 0 ok
return sub
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
Using the BigDecimal standard library:
<langsyntaxhighlight lang="ruby">require "bigdecimal"
 
LN2 = BigMath::log(2,16) #Use LN2 = Math::log(2) to see the difference with floats
Line 2,218:
str = nearly_int?(h) ? "nearly integer" : "NOT nearly integer"
puts "n:%3i h: %s\t%s" % [n, h.to_s('F')[0,25], str] #increase the 25 to print more digits, there are 856 of them
end</langsyntaxhighlight>
{{out}}
<pre>
Line 2,240:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
use decimal::d128;
use factorial::Factorial;
Line 2,261:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,285:
=={{header|Scala}}==
===Functional Programming ♫===
<langsyntaxhighlight Scalalang="scala">import scala.annotation.tailrec
 
object Hickerson extends App {
Line 2,310:
println(s"While h(n) gives NOT an almost integer with a n of ${aa.filter(!_._2).map(_._1).mkString(", ")}.")
 
}</langsyntaxhighlight>
{{Out}}See it in running in your browser by [https://scalafiddle.io/sf/tNNk9jB/2 ScalaFiddle (JavaScript executed in browser)]
or by [https://scastie.scala-lang.org/aX6X59zrTkWpEbCOXmpmAg Scastie (remote JVM)].
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigrat.s7i";
 
Line 2,331:
stri[succ(pos(stri, '.'))] in {'0', '9'});
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,355:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func h(n) {
n! / (2 * pow(2.log, n+1))
}
Line 2,362:
"h(%2d) = %22s is%s almost an integer.\n".printf(
n, var hn = h(n).round(-3), hn.to_s ~~ /\.[09]/ ? '' : ' NOT')
} << 1..17</langsyntaxhighlight>
{{out}}
<pre>h( 1) = 1.041 is almost an integer.
Line 2,384:
=={{header|Tcl}}==
{{tcllib|math::bigfloat}}
<langsyntaxhighlight lang="tcl">package require math::bigfloat
namespace import math::bigfloat::*
 
Line 2,401:
set almost [regexp {\.[09]} $h]
puts [format "h(%d) = %s (%salmost integer)" $n $h [expr {$almost ? "" : "not "}]]
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,424:
 
=={{header|TI-83 BASIC}}==
<langsyntaxhighlight lang="ti83b">For(N,1,17
N!/(2ln(2)^(N+1→H
Disp N,H,"IS
Line 2,431:
Disp "NOT
Disp "ALMOST INTEGER
End</langsyntaxhighlight>
(untested)
 
Line 2,441:
 
I've therefore used the most accurate value I could find for log2 (63 digit accuracy), represented this as a BigInt, and worked from there.
<langsyntaxhighlight lang="ecmascript">import "/math" for Int
import "/fmt" for Fmt
import "/big" for BigInt
Line 2,460:
var s = h[0...k] + "." + h[k]
Fmt.print("$2d: $20s $s", i, s, ai)
}</langsyntaxhighlight>
 
{{out}}
Line 2,487:
 
The following produces the same results as before though is slower than the BigInt version due to the implicit conversions needed.
<langsyntaxhighlight lang="ecmascript">import "/math" for Int
import "/fmt" for Fmt
import "/big" for BigRat
Line 2,503:
var ai = (hl == "0" || hl == "9")
Fmt.print("$2d: $20s $s", i, h, ai)
}</langsyntaxhighlight>
 
=={{header|zkl}}==
Uses lib GMP (integer) and some fiddling to fake up the floating point math.
<langsyntaxhighlight lang="zkl">var [const] BN=Import("zklBigNum"),
X =BN("1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
ln2X=BN("693147180559945309417232121458176568075500134360255254120680009493393621969694715605863326996418687")
;
fcn hickerson(n){ BN(n).factorial()*X.pow(n+1)*10/2/ln2X.pow(n+1) }</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">foreach n in ([1..18]){
hs,ld,isH:=hickerson(n).toString(),hs[-1],"90".holds(ld);
println("h(%2d)=%s.%s almost integer: %b".fmt(n,hs[0,-1],ld,isH));
}</langsyntaxhighlight>
{{out}}
<pre>
10,327

edits