Wolfram Research

NthDigit

Contributed by: Paco Jain (Wolfram Research)

Source Notebook

Computes the digit in a given place of the positional representation of a number

ResourceFunction["NthDigit"][x,n]

Returns the nth base-10 digit of x.

ResourceFunction["NthDigit"][x,n,base]

Returns the nth digit of x in the specified base.

Details and Options

ResourceFunction["NthDigit"][x,n] returns the nth most significant digit of x when expressed in standard positional form, padding with zeros to the right of the decimal if necessary.
For numbers x<1, ResourceFunction["NthDigit"][x, 1] gives 0 and ResourceFunction["NthDigit"][x, n] gives the digit n-1 places to the right of the decimal point.
If n is larger than Precision[x]/Log[10, b], then ResourceFunction["NthDigit"][x,n,b] returns Indeterminate.
The base b in ResourceFunction["NthDigit"][x,n,b] need not be an integer. For any real b such that b > 1, ResourceFunction["NthDigit"][x,n,b] finds the largest integer multiples of bn that can be subtracted from x while leaving a non-negative remainder.
ResourceFunction["NthDigit"][x,n,b] discards the sign of b.

Examples

Basic Examples

Compute the nth digit of a given number:

In[1]:=
ResourceFunction["NthDigit"][123.45, 4]
Out[1]=

Give the 2500th digit of π in base-10:

In[2]:=
ResourceFunction["NthDigit"][Pi, 2500]
Out[2]=

Compute the base-10 digits of a number less than 1:

In[3]:=
ResourceFunction["NthDigit"][3/10, 2]
Out[3]=
In[4]:=
ResourceFunction["NthDigit"][0.012345, #] & /@ Range[10]
Out[4]=

Give the first 10 digit of 19/7 in base 3:

In[5]:=
ResourceFunction["NthDigit"][19/7, #, 3] & /@ Range[10]
Out[5]=

Scope

Noninteger bases are allowed:

In[6]:=
ResourceFunction["NthDigit"][Pi, 9, 3 GoldenRatio]
Out[6]=

Applications

Compute the number of 1s in the first 10^4 binary digits of π:

In[7]:=
Count[ResourceFunction["NthDigit"][Pi, #, 2] & /@ Range[10^4], 1]
Out[7]=

Plot the distribution of first 10,000 digits of π in base-47:

In[8]:=
ListPlot[BinCounts[
  ResourceFunction["NthDigit"][Pi, #, 47] & /@ Range[10000], {0, 46}],
  DataRange -> {0, 46}]
Out[8]=

Properties and Relations

NthDigit ignores the sign of its first argument:

In[9]:=
ResourceFunction["NthDigit"][-Sqrt[2], 1]
Out[9]=

NthDigit gives Indeterminate if more digits than the precision are requested:

In[10]:=
ResourceFunction["NthDigit"][5.635`10, 20]
Out[10]=
In[11]:=
ResourceFunction["NthDigit"][5.635`100, 20]
Out[11]=

Possible Issues

Positional representations only work for bases greater than 1. Using an unsuitable base triggers a message:

In[12]:=
ResourceFunction["NthDigit"][Pi, 3, 1/GoldenRatio]
Out[12]=

Resource History