Natural Breaks (Jenks) returns wrong classes: zero-padded sample above 30009 features, off-by-one in backtracking, unsorted breaks when classes >= features
What is the bug or the crash?
QgsClassificationJenks::calculateBreaks() (Graduated renderer, Mode "Natural Breaks (Jenks)"; also QgsClassificationJenks in PyQGIS) has three independent defects. All three are in current master (b3a180c) and in release-4_0, release-4_2, release-3_40 and release-3_44; I reproduced them on 3.34.4, where the function is the same.
1. Above 30009 features the sample contains zeros that are not in the data.
The sample is resized to std::max( mMaximumSize, values.size() / 10 ) (L90), but the fill loop computes its slot counter from mMaximumSize (L109-L113), so it writes only 3000 slots. For n > 30009 (integer division), the remaining n/10 - 3000 slots keep the value-initialised 0.0 and are classified as data. On a layer whose values are all between 10 and 20, the first class becomes 10.0 to 0.0 (inverted) and a second class starts at 0.0.
2. The backtracking steps back one value too far.
matrixOne[l][j] = i4 (L172) stores i4 = i3 - 1, the 1-based index of the last value of the previous class. id = matrixOne[k][j] - 1 then reads the right break, but the next step k = matrixOne[k][j] - 1 (L189) drops the last value of the previous class before looking up its break. With three or more classes the result can be far from the optimal partition. For the values 1, 2, 3, 50, 100, 101, 102 and 3 classes, QGIS returns upper bounds 1, 50, 102 (within-class sum of squares 1506.7) where the optimum is 3, 50, 102 (sum of squares 4.0). With two classes the step is never used, so two-class results are correct. R's classInt::classIntervals(style = "jenks"), which the code comment cites as its source, stores i3 and steps to i3 - 1, and returns 3, 50, 102.
3. When the number of classes is >= the number of values, the values are returned unsorted.
if ( nclasses >= values.size() ) return values; (L75-L78) returns the attribute values in feature order, so the classes overlap and some are inverted. This looks like the cause of #64429 (closed for lack of data), whose ranges have exactly this pattern.
Steps to reproduce the issue
All three can be run in the Python console (or headless PyQGIS). Output below is from QGIS 3.34.4.
from qgis.core import QgsVectorLayer, QgsFeature, QgsGeometry, QgsPointXY, QgsClassificationJenks
import random
def layer(values):
vl = QgsVectorLayer("Point?crs=EPSG:4326&field=v:double", "t", "memory")
feats = []
for i, x in enumerate(values):
f = QgsFeature(vl.fields())
f.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(i % 1000, i // 1000)))
f.setAttributes([x])
feats.append(f)
vl.dataProvider().addFeatures(feats)
return vl
def jenks(values, k):
return [(round(r.lowerBound(), 3), round(r.upperBound(), 3))
for r in QgsClassificationJenks().classes(layer(values), "v", k)]
# 1. zero padding: every value is between 10 and 20
rng = random.Random(1)
for n in (20000, 60000):
print(n, jenks([rng.uniform(10, 20) for _ in range(n)], 5))
# 2. backtracking: the optimal 3-class upper bounds are 3, 50, 102
print(jenks([1, 2, 3, 50, 100, 101, 102], 3))
# 3. classes >= values
print(jenks([50, 10, 40, 20, 30], 5))Output (QGIS 3.34.4):
20000 [(10.001, 11.991), (11.991, 13.988), (13.988, 15.96), (15.96, 17.962), (17.962, 20.0)]
60000 [(10.0, 0.0), (0.0, 12.531), (12.531, 15.037), (15.037, 17.526), (17.526, 20.0)]
[(1.0, 1.0), (1.0, 50.0), (50.0, 102.0)]
[(10.0, 50.0), (50.0, 10.0), (10.0, 40.0), (40.0, 20.0), (20.0, 30.0)]Expected: (1) no bound outside 10 to 20, as at n = 20000; (2) upper bounds 3, 50, 102; (3) sorted bounds 10, 20, 30, 40, 50.
The same happens in the desktop: Layer Properties > Symbology > Graduated, Mode "Natural Breaks (Jenks)", Classify, on a layer with the values above (QgsGraduatedSymbolRenderer::updateClasses() calls the same classes()).
Versions
QGIS version 3.34.4-Prizren (Ubuntu 24.04 package, headless PyQGIS, Qt offscreen) PROJ 9.4.0, GEOS 3.12.1, GDAL 3.8.4
I have not run a 4.x binary. The function body is unchanged in master at b3a180c (4.3 development), release-4_2, release-4_0, release-3_44 and release-3_40 (source checked on 2026-09-25), and the sampling loop has been the same since 3.20.
Supported QGIS version
- I'm running a supported QGIS version according to the roadmap.
New profile
- I tried with a new QGIS profile
No Duplicate of the Issue
- I have verified that there are no existing issues raised related to my problem.
Additional context
Possible fixes (untested):
- Fill the whole sample, or resize it to
mMaximumSizeonly. If the counter usessample.size(), compute it in 64-bit, sincei * ( mMaximumSize - 2 )already exceedsINT_MAXabove about 716000 features. - Step back with
k = matrixOne[k][j];(keepid = matrixOne[k][j] - 1for the break). A port of the function with this one change returns the same breaks asclassInt::classIntervals(style = "jenks")on every case I tried, including the example above. - Sort (and ideally de-duplicate) the values before returning them when
nclasses >= values.size().
Related: #28299 (open, 3.4) reports a Natural Breaks first class holding a single value with the other classes wrong, which is the symptom of defect 2 in the example above; I could not get its data to confirm. #31723 (unstable breaks in 3.8) matches the random sample used before 3.20, which the current systematic loop replaced.
Source: qgis/QGIS