Movatterモバイル変換


[0]ホーム

URL:


D Logo
Menu
Search

Library Reference

version 2.112.0

overview

Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.Requires a signed-in GitHub account. This works well for small changes.If you'd like to make larger changes you may want to consider usinga local clone.

std.numeric

This module is a port of a growing fragment of thenumericheader in Alexander Stepanov'sStandard Template Library, with a few additions.
License:
Boost License 1.0.
Authors:
Andrei Alexandrescu, Don Clugston, Robert Jacques, Ilya Yaroshenko

Sourcestd/numeric.d

enumCustomFloatFlags: int;
Format flags for CustomFloat.
signed
Adds a sign bit to allow for signed numbers.
storeNormalized
Store values in normalized form by default. The actual precision of the significand is extended by 1 bit by assuming an implicit leading bit of 1 instead of 0. i.e.1.nnnn instead of0.nnnn. True for allIEEE754 types
allowDenorm
Stores the significand in IEEE754 denormalized form when the exponent is 0. Required to express the value 0.
infinity
Allows the storage of IEEE754 infinity values.
nan
Allows the storage ofIEEE754 Not a Number values.
probability
If set, select an exponent bias such that max_exp = 1. i.e. so that the maximum value is >= 1.0 and < 2.0. Ignored if the exponent bias is manually specified.
negativeUnsigned
If set, unsigned custom floats are assumed to be negative.
allowDenormZeroOnly
If set, 0 is the only allowed IEEE754 denormalized number. Requires allowDenorm and storeNormalized.
ieee
Include all of theIEEE754 options.
none
Include none of the above options.
templateCustomFloat(uint bits) if (bits == 8 || bits == 16 || bits == 32 || bits == 64 || bits == 80)

templateCustomFloat(uint precision, uint exponentWidth, CustomFloatFlags flags = CustomFloatFlags.ieee) if (((flags & flags.signed) + precision + exponentWidth) % 8 == 0 && (precision + exponentWidth > 0))

structCustomFloat(uint precision, uint exponentWidth, CustomFloatFlags flags, uint bias) if (isCorrectCustomFloat(precision, exponentWidth, flags));
Allows user code to define custom floating-point formats. These formats are for storage only; all operations on them are performed by first implicitly extracting them toreal first. After the operation is completed the result can be stored in a custom floating-point value via assignment.
Examples:
import std.math.trigonometry : sin, cos;// Define a 16-bit floating point valuesCustomFloat!16                                x;// Using the number of bitsCustomFloat!(10, 5)                           y;// Using the precision and exponent widthCustomFloat!(10, 5,CustomFloatFlags.ieee)     z;// Using the precision, exponent width and format flagsCustomFloat!(10, 5,CustomFloatFlags.ieee, 15) w;// Using the precision, exponent width, format flags and exponent offset bias// Use the 16-bit floats mostly like normal numbersw = x*y - 1;// Functions calls require conversionz = sin(+x)           + cos(+y);// Use unary plus to concisely convert to a realz = sin(x.get!float)  + cos(y.get!float);// Or use get!Tz = sin(cast(float) x) + cos(cast(float) y);// Or use cast(T) to explicitly convert// Define a 8-bit custom float for storing probabilitiesalias Probability =CustomFloat!(4, 4, CustomFloatFlags.ieee^CustomFloatFlags.probability^CustomFloatFlags.signed );auto p = Probability(0.5);
templateFPTemporary(F) if (isFloatingPoint!F)
Defines the fastest type to use when storing temporaries of acalculation intended to ultimately yield a result of typeF(whereF must be one offloat,double, orreal). When doing a multi-step computation, you may want to storeintermediate results asFPTemporary!F.
The necessity ofFPTemporary stems from the optimizedfloating-point operations and registers present in virtually allprocessors. When adding numbers in the example above, the addition mayin fact be done inreal precision internally. In that case,storing the intermediateresult indouble format is not onlyless precise, it is also (surprisingly) slower, because a conversionfromreal todouble is performed every pass through theloop. This being a lose-lose situation,FPTemporary!F has beendefined as thefastest type to use for calculations at precisionF. There is no need to define a type for themost accuratecalculations, as that is alwaysreal.
Finally, there is no guarantee that usingFPTemporary!F willalways be fastest, as the speed of floating-point calculations dependson very many factors.
Examples:
import std.math.operations : isClose;// Average numbers in an arraydouble avg(indouble[] a){if (a.length == 0)return 0;FPTemporary!double result = 0;foreach (e; a) result += e;return result / a.length;}auto a = [1.0, 2.0, 3.0];assert(isClose(avg(a), 2));
templatesecantMethod(alias fun)
Implements thesecant method for finding aroot of the functionfun starting from points[xn_1, x_n](ideally close to the root).Num may befloat,double,orreal.
Examples:
import std.math.operations : isClose;import std.math.trigonometry : cos;float f(float x){return cos(x) - x*x*x;}auto x =secantMethod!(f)(0f, 1f);assert(isClose(x, 0.865474));
TfindRoot(T, DF, DT)(scope DFf, const Ta, const Tb, scope DTtolerance)
if (isFloatingPoint!T && is(typeof(tolerance(T.init, T.init)) : bool) && is(typeof(f(T.init)) == R, R) && isFloatingPoint!R);

TfindRoot(T, DF)(scope DFf, const Ta, const Tb);
Find a real root of a real function f(x) via bracketing.
Given a functionf and a range[a ..b] such thatf(a) andf(b) have opposite signs or at least one of them equals ±0, returns the value ofx in the range which is closest to a root off(x). Iff(x) has more than one root in the range, one will be chosen arbitrarily. Iff(x) returns NaN, NaN will be returned; otherwise, this algorithm is guaranteed to succeed.
Uses an algorithm based on TOMS748, which uses inverse cubic interpolation whenever possible, otherwise reverting to parabolic or secant interpolation. Compared to TOMS748, this implementation improves worst-case performance by a factor of more than 100, and typical performance by a factor of 2. For 80-bit reals, most problems require 8 to 15 calls tof(x) to achieve full machine precision. The worst-case performance (pathological cases) is approximately twice the number of bits.

References"On Enclosing Simple Roots of Nonlinear Equations", G. Alefeld, F.A. Potra, Yixun Shi, Mathematics of Computation 61, pp733-744 (1993). Fortran code available fromwww.netlib.org as algorithm TOMS478.

Tuple!(T, T, R, R)findRoot(T, R, DF, DT)(scope DFf, const Tax, const Tbx, const Rfax, const Rfbx, scope DTtolerance)
if (isFloatingPoint!T && is(typeof(tolerance(T.init, T.init)) : bool) && is(typeof(f(T.init)) == R) && isFloatingPoint!R);

Tuple!(T, T, R, R)findRoot(T, R, DF)(scope DFf, const Tax, const Tbx, const Rfax, const Rfbx);

TfindRoot(T, R)(scope R delegate(T)f, const Ta, const Tb, scope bool delegate(T lo, T hi)tolerance = (Ta, Tb) => false);
Find root of a real function f(x) by bracketing, allowing the termination condition to be specified.
Parameters:
DFfFunction to be analyzed
TaxLeft bound of initial range off known to contain the root.
TbxRight bound of initial range off known to contain the root.
RfaxValue off(ax).
RfbxValue off(bx).fax andfbx should have opposite signs. (f(ax) andf(bx) are commonly known in advance.)
DTtoleranceDefines an early termination condition. Receives the current upper and lower bounds on the root. The delegate must returntrue when these bounds are acceptable. If this function always returnsfalse, full machine precision will be achieved.
Returns:
A tuple consisting of two ranges. The first two elements are the range (inx) of the root, while the second pair of elements are the corresponding function values at those points. If an exact root was found, both of the first two elements will contain the root, and the second pair of elements will be 0.
Tuple!(T, "x", Unqual!(ReturnType!DF), "y", T, "error")findLocalMin(T, DF)(scope DFf, const Tax, const Tbx, const TrelTolerance = sqrt(T.epsilon), const TabsTolerance = sqrt(T.epsilon))
if (isFloatingPoint!T && __traits(compiles, (){T _ = DF.init(T.init);}));
Find a real minimum of a real functionf(x) via bracketing.Given a functionf and a range(ax ..bx),returns the value ofx in the range which is closest to a minimum off(x).f is never evaluted at the endpoints ofax andbx.Iff(x) has more than one minimum in the range, one will be chosen arbitrarily.Iff(x) returns NaN or -Infinity,(x,f(x), NaN) will be returned;otherwise, this algorithm is guaranteed to succeed.
Parameters:
DFfFunction to be analyzed
TaxLeft bound of initial range of f known to contain the minimum.
TbxRight bound of initial range of f known to contain the minimum.
TrelToleranceRelative tolerance.
TabsToleranceAbsolute tolerance.

Preconditionsax andbx shall be finite reals.
relTolerance shall be normal positive real.
absTolerance shall be normal positive real no less thenT.epsilon*2.

Returns:
A tuple consisting ofx,y =f(x) anderror = 3 * (absTolerance * fabs(x) +relTolerance).
The method used is a combination of golden section search andsuccessive parabolic interpolation. Convergence is never much slowerthan that for a Fibonacci search.

References"Algorithms for Minimization without Derivatives", Richard Brent, Prentice-Hall, Inc. (1973)

See Also:
Examples:
import std.math.operations : isClose;auto ret =findLocalMin((double x) => (x-4)^^2, -1e7, 1e7);assert(ret.x.isClose(4.0));assert(ret.y.isClose(0.0, 0.0, 1e-10));
CommonType!(ElementType!Range1, ElementType!Range2)euclideanDistance(Range1, Range2)(Range1a, Range2b)
if (isInputRange!Range1 && isInputRange!Range2);

CommonType!(ElementType!Range1, ElementType!Range2)euclideanDistance(Range1, Range2, F)(Range1a, Range2b, Flimit)
if (isInputRange!Range1 && isInputRange!Range2);
ComputesEuclidean distance between input rangesa andb. The two ranges must have the same length. The three-parameterversion stops computation as soon as the distance is greater than orequal tolimit (this is useful to save computation if a smalldistance is sought).
CommonType!(ElementType!Range1, ElementType!Range2)dotProduct(Range1, Range2)(Range1a, Range2b)
if (isInputRange!Range1 && isInputRange!Range2 && !(isArray!Range1 && isArray!Range2));

CommonType!(F1, F2)dotProduct(F1, F2)(in F1[]avector, in F2[]bvector);

FdotProduct(F, uint N)(ref scope const F[N]a, ref scope const F[N]b)
if (N <= 16);
Computes thedot product of input rangesa andb. The two ranges must have the same length. If both ranges definelength, the check is done once; otherwise, it is done at eachiteration.
CommonType!(ElementType!Range1, ElementType!Range2)cosineSimilarity(Range1, Range2)(Range1a, Range2b)
if (isInputRange!Range1 && isInputRange!Range2);
Computes thecosine similarity of input rangesa andb. The two ranges must have the same length. If both ranges definelength, the check is done once; otherwise, it is done at eachiteration. If either range has all-zero elements, return 0.
boolnormalize(R)(Rrange, ElementType!Rsum = 1)
if (isForwardRange!R);
Normalizes values inrange by multiplying each element with anumber chosen such that values sum up tosum. If elements inrange sum to zero, assignssum / range.length toall. Normalization makes sense only if all elements inrange arepositive.normalize assumes that is the case without checking it.
Returns:
true if normalization completed normally,false ifall elements inrange were zero or ifrange is empty.
Examples:
double[] a = [];assert(!normalize(a));a = [ 1.0, 3.0 ];assert(normalize(a));writeln(a);// [0.25, 0.75]assert(normalize!(typeof(a))(a, 50));// a = [12.5, 37.5]a = [ 0.0, 0.0 ];assert(!normalize(a));writeln(a);// [0.5, 0.5]
ElementType!RangesumOfLog2s(Range)(Ranger)
if (isInputRange!Range && isFloatingPoint!(ElementType!Range));
Compute the sum of binary logarithms of the input ranger.The error of this method is much smaller than with a naive sum of log2.
Examples:
import std.math.traits : isNaN;writeln(sumOfLog2s(newdouble[0]));// 0writeln(sumOfLog2s([0.0L]));// -real.infinitywriteln(sumOfLog2s([-0.0L]));// -real.infinitywriteln(sumOfLog2s([2.0L]));// 1assert(sumOfLog2s([-2.0L]).isNaN());assert(sumOfLog2s([real.nan]).isNaN());assert(sumOfLog2s([-real.nan]).isNaN());writeln(sumOfLog2s([real.infinity]));// real.infinityassert(sumOfLog2s([-real.infinity]).isNaN());writeln(sumOfLog2s([0.25, 0.25, 0.25, 0.125]));// -9
ElementType!Rangeentropy(Range)(Ranger)
if (isInputRange!Range);

ElementType!Rangeentropy(Range, F)(Ranger, Fmax)
if (isInputRange!Range && !is(CommonType!(ElementType!Range, F) == void));
Computesentropy of input ranger in bits. Thisfunction assumes (without checking) that the values inr are allin[0, 1]. For the entropy to be meaningful, oftenr shouldbe normalized too (i.e., its values should sum to 1). Thetwo-parameter version stops evaluating as soon as the intermediateresult is greater than or equal tomax.
CommonType!(ElementType!Range1, ElementType!Range2)kullbackLeiblerDivergence(Range1, Range2)(Range1a, Range2b)
if (isInputRange!Range1 && isInputRange!Range2);
Computes theKullback-Leibler divergence between input rangesa andb, which is the sumai * log(ai / bi). The baseof logarithm is 2. The ranges are assumed to contain elements in[0, 1]. Usually the ranges are normalized probability distributions,but this is not required or checked bykullbackLeiblerDivergence. If any elementbi is zero and thecorresponding elementai nonzero, returns infinity. (Otherwise,ifai == 0 && bi == 0, the termai * log(ai / bi) isconsidered zero.) If the inputs are normalized, the result ispositive.
Examples:
import std.math.operations : isClose;double[] p = [ 0.0, 0, 0, 1 ];writeln(kullbackLeiblerDivergence(p, p));// 0double[] p1 = [ 0.25, 0.25, 0.25, 0.25 ];writeln(kullbackLeiblerDivergence(p1, p1));// 0writeln(kullbackLeiblerDivergence(p, p1));// 2writeln(kullbackLeiblerDivergence(p1, p));// double.infinitydouble[] p2 = [ 0.2, 0.2, 0.2, 0.4 ];assert(isClose(kullbackLeiblerDivergence(p1, p2), 0.0719281, 1e-5));assert(isClose(kullbackLeiblerDivergence(p2, p1), 0.0780719, 1e-5));
CommonType!(ElementType!Range1, ElementType!Range2)jensenShannonDivergence(Range1, Range2)(Range1a, Range2b)
if (isInputRange!Range1 && isInputRange!Range2 && is(CommonType!(ElementType!Range1, ElementType!Range2)));

CommonType!(ElementType!Range1, ElementType!Range2)jensenShannonDivergence(Range1, Range2, F)(Range1a, Range2b, Flimit)
if (isInputRange!Range1 && isInputRange!Range2 && is(typeof(CommonType!(ElementType!Range1, ElementType!Range2).init >= F.init) : bool));
Computes theJensen-Shannon divergence betweena andb, which is the sum(ai * log(2 * ai / (ai + bi)) + bi * log(2 *bi / (ai + bi))) / 2. The base of logarithm is 2. The ranges areassumed to contain elements in[0, 1]. Usually the ranges arenormalized probability distributions, but this is not required orchecked byjensenShannonDivergence. If the inputs are normalized,the result is bounded within[0, 1]. The three-parameter versionstops evaluations as soon as the intermediate result is greater thanor equal tolimit.
Examples:
import std.math.operations : isClose;double[] p = [ 0.0, 0, 0, 1 ];writeln(jensenShannonDivergence(p, p));// 0double[] p1 = [ 0.25, 0.25, 0.25, 0.25 ];writeln(jensenShannonDivergence(p1, p1));// 0assert(isClose(jensenShannonDivergence(p1, p), 0.548795, 1e-5));double[] p2 = [ 0.2, 0.2, 0.2, 0.4 ];assert(isClose(jensenShannonDivergence(p1, p2), 0.0186218, 1e-5));assert(isClose(jensenShannonDivergence(p2, p1), 0.0186218, 1e-5));assert(isClose(jensenShannonDivergence(p2, p1, 0.005), 0.00602366, 1e-5));
FgapWeightedSimilarity(alias comp = "a == b", R1, R2, F)(R1s, R2t, Flambda)
if (isRandomAccessRange!R1 && hasLength!R1 && isRandomAccessRange!R2 && hasLength!R2);
The so-called "all-lengths gap-weighted string kernel" computes asimilarity measure betweens andt based on all of theircommon subsequences of all lengths. Gapped subsequences are alsoincluded.
To understand whatgapWeightedSimilarity(s, t, lambda) computes,consider first the caselambda = 1 and the stringss =["Hello", "brave", "new", "world"] andt = ["Hello", "new","world"]. In that case,gapWeightedSimilarity counts thefollowing matches:
  1. three matches of length 1, namely"Hello","new",and"world";
  2. three matches of length 2, namely ("Hello", "new"), ("Hello", "world"), and ("new", "world");
  3. one match of length 3, namely ("Hello", "new", "world").
The callgapWeightedSimilarity(s, t, 1) simply counts all ofthese matches and adds them up, returning 7.
string[]s = ["Hello","brave","new","world"];string[]t = ["Hello","new","world"];assert(gapWeightedSimilarity(s,t, 1) == 7);
Note how the gaps in matching are simply ignored, for example ("Hello", "new") is deemed as good a match as ("new","world"). This may be too permissive for some applications. Toeliminate gapped matches entirely, uselambda = 0:
string[]s = ["Hello","brave","new","world"];string[]t = ["Hello","new","world"];assert(gapWeightedSimilarity(s,t, 0) == 4);
The call above eliminated the gapped matches ("Hello", "new"),("Hello", "world"), and ("Hello", "new", "world") from thetally. That leaves only 4 matches.
The most interesting case is when gapped matches still participate inthe result, but not as strongly as ungapped matches. The result willbe a smooth, fine-grained similarity measure between the inputstrings. This is where values oflambda between 0 and 1 enterinto play: gapped matches areexponentially penalized with thenumber of gaps with baselambda. This means that an ungappedmatch adds 1 to the return value; a match with one gap in eitherstring addslambda to the return value; ...; a match with a totalofn gaps in both strings addspow(lambda, n) to the returnvalue. In the example above, we have 4 matches without gaps, 2 matcheswith one gap, and 1 match with three gaps. The latter match is ("Hello", "world"), which has two gaps in the first string and one gapin the second string, totaling to three gaps. Summing these up we get4 + 2 * lambda + pow(lambda, 3).
string[]s = ["Hello","brave","new","world"];string[]t = ["Hello","new","world"];assert(gapWeightedSimilarity(s,t, 0.5) == 4 + 0.5 * 2 + 0.125);
gapWeightedSimilarity is useful wherever a smooth similaritymeasure between sequences allowing for approximate matches isneeded. The examples above are given with words, but any sequenceswith elements comparable for equality are allowed, e.g. characters ornumbers.gapWeightedSimilarity uses a highly optimized dynamicprogramming implementation that needs16 * min(s.length,t.length) extra bytes of memory andΟ(s.length * t.length) timeto complete.
Select!(isFloatingPoint!F, F, double)gapWeightedSimilarityNormalized(alias comp = "a == b", R1, R2, F)(R1s, R2t, Flambda, FsSelfSim = F.init, FtSelfSim = F.init)
if (isRandomAccessRange!R1 && hasLength!R1 && isRandomAccessRange!R2 && hasLength!R2);
The similarity pergapWeightedSimilarity has an issue in that itgrows with the lengths of the two strings, even though the strings arenot actually very similar. For example, the range["Hello","world"] is increasingly similar with the range["Hello","world", "world", "world",...] as more instances of"world" areappended. To prevent that,gapWeightedSimilarityNormalizedcomputes a normalized version of the similarity that is computed asgapWeightedSimilarity(s, t, lambda) /sqrt(gapWeightedSimilarity(s, t, lambda) * gapWeightedSimilarity(s, t,lambda)). The functiongapWeightedSimilarityNormalized (aso-called normalized kernel) is bounded in[0, 1], reaches0only for ranges that don't match in any position, and1 only foridentical ranges.
The optional parameterssSelfSim andtSelfSim are meant foravoiding duplicate computation. Many applications may have alreadycomputedgapWeightedSimilarity(s, s, lambda) and/orgapWeightedSimilarity(t, t, lambda). In that case, they can be passedassSelfSim andtSelfSim, respectively.
Examples:
import std.math.operations : isClose;import std.math.algebraic : sqrt;string[]s = ["Hello","brave","new","world"];string[]t = ["Hello","new","world"];writeln(gapWeightedSimilarity(s,s, 1));// 15writeln(gapWeightedSimilarity(t,t, 1));// 7writeln(gapWeightedSimilarity(s,t, 1));// 7assert(isClose(gapWeightedSimilarityNormalized(s,t, 1),                7.0 / sqrt(15.0 * 7), 0.01));
structGapWeightedSimilarityIncremental(Range, F = double) if (isRandomAccessRange!Range && hasLength!Range);

GapWeightedSimilarityIncremental!(R, F)gapWeightedSimilarityIncremental(R, F)(Rr1, Rr2, Fpenalty);
Similar togapWeightedSimilarity, just works in an incrementalmanner by first revealing the matches of length 1, then gapped matchesof length 2, and so on. The memory requirement isΟ(s.length *t.length). The time complexity isΟ(s.length * t.length) timefor computing each step. Continuing on the previous example:
The implementation is based on the pseudocode in Fig. 4 of the paper"Efficient Computation of Gapped Substring Kernels on Large Alphabets"by Rousu et al., with additional algorithmic and systems-leveloptimizations.
Examples:
string[] s = ["Hello","brave","new","world"];string[] t = ["Hello","new","world"];auto simIter =gapWeightedSimilarityIncremental(s, t, 1.0);assert(simIter.front == 3);// three 1-length matchessimIter.popFront();assert(simIter.front == 3);// three 2-length matchessimIter.popFront();assert(simIter.front == 1);// one 3-length matchsimIter.popFront();assert(simIter.empty);// no more match
this(Ranges, Ranget, Flambda);
Constructs an object given two rangess andt and a penaltylambda. Constructor completes inΟ(s.length * t.length)time and computes all matches of length 1.
ref GapWeightedSimilarityIncrementalopSlice();
Returns:
this.
voidpopFront();
Computes the match of the popFront length. Completes inΟ(s.length * t.length) time.
@property Ffront();
Returns:
The gapped similarity at the current match length (initially 1, grows with each call topopFront).
@property boolempty();
Returns:
Whether there are more matches.
typeof(Unqual!T.init % Unqual!U.init)gcd(T, U)(Ta, Ub)
if (isIntegral!T && isIntegral!U);

autogcd(T)(Ta, Tb)
if (!isIntegral!T && is(typeof(T.init % T.init)) && is(typeof(T.init == 0 || T.init > 0)));
Computes the greatest common divisor ofa andb by usingan efficient algorithm such asEuclid'sorStein's algorithm.
Parameters:
TaInteger value of any numerical type that supports the modulo operator%. If bit-shifting<< and>> are also supported, Stein's algorithm will be used; otherwise, Euclid's algorithm is used as a fallback.
UbInteger value of any equivalent numerical type.
Returns:
The greatest common divisor of the given arguments.
typeof(Unqual!T.init % Unqual!U.init)lcm(T, U)(Ta, Ub)
if (isIntegral!T && isIntegral!U);

autolcm(T)(Ta, Tb)
if (!isIntegral!T && is(typeof(T.init % T.init)) && is(typeof(T.init == 0 || T.init > 0)));
Computes the least common multiple ofa andb.Arguments are the same asgcd .
Returns:
The least common multiple of the given arguments.
Examples:
writeln(lcm(1, 2));// 2writeln(lcm(3, 4));// 12writeln(lcm(5, 6));// 30
classFft;
A class for performing fast Fourier transforms of power of two sizes. This class encapsulates a large amount of state that is reusable when performing multiple FFTs of sizes smaller than or equal to that specified in the constructor. This results in substantial speedups when performing multiple FFTs with a known maximum size. However, a free function API is provided for convenience if you need to perform a one-off FFT.

Referencesen.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm

this(size_tsize);
Create anFft object for computing fast Fourier transforms of power of two sizes ofsize or smaller.size must be a power of two.
Complex!F[]fft(F = double, R)(Rrange) const
if (isFloatingPoint!F && isRandomAccessRange!R);
Compute the Fourier transform of range using theΟ(N log N) Cooley-Tukey Algorithm.range must be a random-access range with slicing and a length equal tosize as provided at the construction of this object. The contents of range can be either numeric types, which will be interpreted as pure real values, or complex types with properties or members.re and.im that can be read.

NotePure real FFTs are automatically detected and the relevant optimizations are performed.

Returns:
An array of complex numbers representing the transformed data in the frequency domain.

ConventionsThe exponent is negative and the factor is one, i.e., output[j] := sum[ exp(-2 PI i j k / N) input[k] ].

voidfft(Ret, R)(Rrange, Retbuf) const
if (isRandomAccessRange!Ret && isComplexLike!(ElementType!Ret) && hasSlicing!Ret);
Same as the overload, but allows for the results to be stored in a user- provided buffer. The buffer must be of the same length as range, must be a random-access range, must have slicing, and must contain elements that are complex-like. This means that they must have a .re and a .im member or property that can be both read and written and are floating point numbers.
Complex!F[]inverseFft(F = double, R)(Rrange) const
if (isRandomAccessRange!R && isComplexLike!(ElementType!R) && isFloatingPoint!F);
Computes the inverse Fourier transform of a range. The range must be a random access range with slicing, have a length equal to the size provided at construction of this object, and contain elements that are either of type std.complex.Complex or have essentially the same compile-time interface.
Returns:
The time-domain signal.

ConventionsThe exponent is positive and the factor is 1/N, i.e., output[j] := (1 / N) sum[ exp(+2 PI i j k / N) input[k] ].

voidinverseFft(Ret, R)(Rrange, Retbuf) const
if (isRandomAccessRange!Ret && isComplexLike!(ElementType!Ret) && hasSlicing!Ret);
Inverse FFT that allows a user-supplied buffer to be provided. The buffer must be a random access range with slicing, and its elements must be some complex-like type.
Complex!F[]fft(F = double, R)(Rrange);

voidfft(Ret, R)(Rrange, Retbuf);

Complex!F[]inverseFft(F = double, R)(Rrange);

voidinverseFft(Ret, R)(Rrange, Retbuf);
Convenience functions that create anFft object, run the FFT or inverse FFT and return the result. Useful for one-off FFTs.

NoteIn addition to convenience, these functions are slightly more efficient than manually creating an Fft object for a single use, as the Fft object is deterministically destroyed before these functions return.

pure nothrow @nogc @safe size_tdecimalToFactorial(ulongdecimal, ref ubyte[21]fac);
This function transformsdecimal value into a value in the factorial numbersystem stored infac.
A factorial number is constructed as:fac[0] * 0! + fac[1] * 1! + ... fac[20] * 20!
Parameters:
ulongdecimalThe decimal value to convert into the factorial number system.
ubyte[21]facThe array to store the factorial number. The array is of size 21 asulong.max requires 21 digits in the factorial number system.
Returns:
A variable storing the number of digits of the factorial number stored infac.
Examples:
ubyte[21]fac;size_t idx =decimalToFactorial(2982,fac);writeln(fac[0]);// 4writeln(fac[1]);// 0writeln(fac[2]);// 4writeln(fac[3]);// 1writeln(fac[4]);// 0writeln(fac[5]);// 0writeln(fac[6]);// 0
Copyright © 1999-2026 by theD Language Foundation | Page generated byDdoc on Sat Feb 21 04:08:02 2026

[8]ページ先頭

©2009-2026 Movatter.jp