1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
|
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sympy import isprime, primerange, nextprime, prevprime import time from functools import lru_cache import warnings warnings.filterwarnings('ignore')
def sieve(limit): """Return array of primes up to `limit` using numpy sieve.""" is_prime = np.ones(limit + 1, dtype=bool) is_prime[0:2] = False for i in range(2, int(limit**0.5) + 1): if is_prime[i]: is_prime[i*i::i] = False return np.where(is_prime)[0]
def goldbach_error(N, primes_arr): """ For a given N, find the pair (p, q) with p, q prime (p <= q) that minimizes |N - (p + q)|. Returns: (min_error, best_p, best_q) """ if N < 4: return N, None, None
candidates = primes_arr[primes_arr <= N] if len(candidates) == 0: return N, None, None
min_err = np.inf best_p, best_q = None, None
for p in candidates: target = N - p if target < 2: break idx = np.searchsorted(candidates, target) for offset in range(-1, 2): j = idx + offset if 0 <= j < len(candidates): q = candidates[j] err = abs(N - (p + q)) if err < min_err: min_err = err best_p, best_q = p, q if min_err == 0: return 0, best_p, best_q
return int(min_err), best_p, best_q
def compute_error_range(N_min, N_max, primes_arr): """ Compute Goldbach errors for all integers in [N_min, N_max]. Returns arrays: N_vals, errors, best_p, best_q """ N_vals = np.arange(N_min, N_max + 1) errors = np.zeros(len(N_vals), dtype=int) p_vals = np.zeros(len(N_vals), dtype=int) q_vals = np.zeros(len(N_vals), dtype=int)
for i, N in enumerate(N_vals): e, p, q = goldbach_error(N, primes_arr) errors[i] = e p_vals[i] = p if p is not None else 0 q_vals[i] = q if q is not None else 0
return N_vals, errors, p_vals, q_vals
def weighted_goldbach_error(N, primes_arr, alpha=1.0, beta=0.5): """ Weighted error: W(N) = alpha * |N - (p+q)| + beta * (gap_p + gap_q) where gap_x = distance from x to nearest prime. Minimized over all prime pairs. """ candidates = primes_arr[primes_arr <= N] if len(candidates) == 0: return N, None, None
min_w = np.inf best_p, best_q = None, None
for p in candidates: target = N - p if target < 2: break idx = np.searchsorted(candidates, target) for offset in range(-1, 2): j = idx + offset if 0 <= j < len(candidates): q = candidates[j] raw_err = abs(N - (p + q)) gap = abs(p - q) w = alpha * raw_err + beta * gap / N if w < min_w: min_w = w best_p, best_q = p, q
return min_w, best_p, best_q
def compute_3d_surface(N_range, alpha_range, primes_arr): """ For each (N, alpha), compute weighted Goldbach error. Returns meshgrid arrays for 3D plotting. """ N_arr = np.array(N_range) A_arr = np.array(alpha_range) Z = np.zeros((len(A_arr), len(N_arr)))
for i, alpha in enumerate(A_arr): for j, N in enumerate(N_arr): w, _, _ = weighted_goldbach_error(N, primes_arr, alpha=alpha, beta=0.5) Z[i, j] = w
NN, AA = np.meshgrid(N_arr, A_arr) return NN, AA, Z
LIMIT = 500 primes_arr = sieve(LIMIT)
print(f"Primes up to {LIMIT}: {len(primes_arr)} primes generated") print(f"First 10: {primes_arr[:10]}") print(f"Last 10: {primes_arr[-10:]}")
N_example = 100 err, p, q = goldbach_error(N_example, primes_arr) print(f"\n--- Example: N = {N_example} ---") print(f"Best pair: ({p}, {q})") print(f"Sum: {p + q}") print(f"Error |{N_example} - ({p}+{q})| = {err}")
N_min, N_max = 4, 200 print(f"\nComputing Goldbach errors for N in [{N_min}, {N_max}]...") t0 = time.time() N_vals, errors, p_vals, q_vals = compute_error_range(N_min, N_max, primes_arr) t1 = time.time() print(f"Done in {t1-t0:.3f}s") print(f"Max error: {errors.max()} at N={N_vals[errors.argmax()]}") print(f"Mean error: {errors.mean():.4f}") print(f"Fraction with error=0 (exact Goldbach): {(errors==0).mean()*100:.1f}%")
N_3d = list(range(10, 101, 5)) alpha_3d = [round(0.2 + 0.2*k, 1) for k in range(10)] print(f"\nBuilding 3D surface ({len(N_3d)} x {len(alpha_3d)} grid)...") t0 = time.time() NN, AA, ZZ = compute_3d_surface(N_3d, alpha_3d, primes_arr) t1 = time.time() print(f"3D grid computed in {t1-t0:.3f}s")
fig = plt.figure(figsize=(20, 18)) fig.patch.set_facecolor('#0d1117')
colors = { 'bg': '#0d1117', 'panel': '#161b22', 'grid': '#21262d', 'text': '#c9d1d9', 'accent':'#58a6ff', 'gold': '#e3b341', 'green': '#3fb950', 'red': '#f85149', 'purple':'#bc8cff', }
def style_ax(ax, title=''): ax.set_facecolor(colors['panel']) ax.tick_params(colors=colors['text'], labelsize=9) ax.title.set_color(colors['text']) ax.xaxis.label.set_color(colors['text']) ax.yaxis.label.set_color(colors['text']) for spine in ax.spines.values(): spine.set_edgecolor(colors['grid']) ax.grid(True, color=colors['grid'], linewidth=0.5, alpha=0.7) if title: ax.set_title(title, fontsize=12, pad=10, color=colors['text'])
ax1 = fig.add_subplot(3, 3, 1) style_ax(ax1, 'Goldbach Error |N − (p+q)| by N') mask0 = errors == 0 mask1 = errors > 0 ax1.bar(N_vals[mask0], errors[mask0], width=0.8, color=colors['green'], alpha=0.7, label='Error = 0 (exact)') ax1.bar(N_vals[mask1], errors[mask1], width=0.8, color=colors['red'], alpha=0.8, label='Error > 0') ax1.set_xlabel('N') ax1.set_ylabel('Error') ax1.legend(fontsize=8, facecolor=colors['panel'], labelcolor=colors['text'], framealpha=0.8)
ax2 = fig.add_subplot(3, 3, 2) style_ax(ax2, 'Cumulative Distribution of Errors') sorted_err = np.sort(errors) cdf = np.arange(1, len(sorted_err)+1) / len(sorted_err) ax2.plot(sorted_err, cdf, color=colors['accent'], linewidth=2) ax2.fill_between(sorted_err, 0, cdf, alpha=0.15, color=colors['accent']) ax2.set_xlabel('Error magnitude') ax2.set_ylabel('Cumulative probability') ax2.axvline(x=0, color=colors['green'], linestyle='--', alpha=0.7, label=f"P(err=0)={(mask0.sum()/len(errors)):.2f}") ax2.legend(fontsize=8, facecolor=colors['panel'], labelcolor=colors['text'], framealpha=0.8)
ax3 = fig.add_subplot(3, 3, 3) style_ax(ax3, 'Prime Pairs (p, q) Minimizing Error') sc = ax3.scatter(p_vals[mask0], q_vals[mask0], c=N_vals[mask0], cmap='plasma', s=20, alpha=0.7, label='Error=0') ax3.scatter(p_vals[mask1], q_vals[mask1], c=colors['red'], s=30, alpha=0.9, marker='x', label='Error>0', linewidths=1.2) cbar = plt.colorbar(sc, ax=ax3) cbar.ax.yaxis.set_tick_params(color=colors['text']) cbar.set_label('N value', color=colors['text']) ax3.set_xlabel('p (first prime)') ax3.set_ylabel('q (second prime)') ax3.legend(fontsize=8, facecolor=colors['panel'], labelcolor=colors['text'], framealpha=0.8)
ax4 = fig.add_subplot(3, 3, 4) style_ax(ax4, 'Error Magnitude Distribution') unique, counts = np.unique(errors, return_counts=True) ax4.bar(unique, counts, color=colors['purple'], alpha=0.8, edgecolor=colors['bg']) ax4.set_xlabel('Error magnitude') ax4.set_ylabel('Frequency') for u, c in zip(unique, counts): ax4.text(u, c + 0.3, str(c), ha='center', va='bottom', fontsize=8, color=colors['text'])
ax5 = fig.add_subplot(3, 3, 5) style_ax(ax5, 'Rolling Mean Error (window=20)') window = 20 roll_mean = np.convolve(errors, np.ones(window)/window, mode='valid') x_roll = N_vals[window-1:] ax5.plot(x_roll, roll_mean, color=colors['gold'], linewidth=1.8) ax5.fill_between(x_roll, 0, roll_mean, alpha=0.2, color=colors['gold']) ax5.set_xlabel('N') ax5.set_ylabel('Rolling mean error')
ax6 = fig.add_subplot(3, 3, 6) style_ax(ax6, 'Weighted Error vs α (N=97, β=0.5)') alphas = np.linspace(0.1, 3.0, 60) N_test = 97 w_vals = [] for a in alphas: w, _, _ = weighted_goldbach_error(N_test, primes_arr, alpha=a, beta=0.5) w_vals.append(w) ax6.plot(alphas, w_vals, color=colors['green'], linewidth=2) ax6.set_xlabel('α (weight on raw error)') ax6.set_ylabel('Weighted error W(N)') ax6.axvline(x=alphas[np.argmin(w_vals)], color=colors['red'], linestyle='--', alpha=0.7, label=f"min at α={alphas[np.argmin(w_vals)]:.2f}") ax6.legend(fontsize=8, facecolor=colors['panel'], labelcolor=colors['text'], framealpha=0.8)
ax7 = fig.add_subplot(3, 3, 7, projection='3d') ax7.set_facecolor(colors['panel']) surf = ax7.plot_surface(NN, AA, ZZ, cmap='inferno', edgecolor='none', alpha=0.9) ax7.set_xlabel('N', color=colors['text'], labelpad=6) ax7.set_ylabel('α', color=colors['text'], labelpad=6) ax7.set_zlabel('W(N,α)', color=colors['text'], labelpad=6) ax7.set_title('3D: Weighted Error Surface W(N, α)', color=colors['text'], fontsize=12, pad=10) ax7.tick_params(colors=colors['text'], labelsize=7) ax7.xaxis.pane.fill = False ax7.yaxis.pane.fill = False ax7.zaxis.pane.fill = False ax7.xaxis.pane.set_edgecolor(colors['grid']) ax7.yaxis.pane.set_edgecolor(colors['grid']) ax7.zaxis.pane.set_edgecolor(colors['grid']) fig.colorbar(surf, ax=ax7, shrink=0.5, label='W(N,α)')
ax8 = fig.add_subplot(3, 3, 8, projection='3d') ax8.set_facecolor(colors['panel']) err_norm = errors / (errors.max() + 1e-9) scatter_colors = plt.cm.RdYlGn(1 - err_norm) ax8.scatter(p_vals, q_vals, N_vals, c=scatter_colors, s=12, alpha=0.7) ax8.set_xlabel('p', color=colors['text'], labelpad=5) ax8.set_ylabel('q', color=colors['text'], labelpad=5) ax8.set_zlabel('N', color=colors['text'], labelpad=5) ax8.set_title('3D: Prime Pair Landscape (p, q, N)', color=colors['text'], fontsize=12, pad=10) ax8.tick_params(colors=colors['text'], labelsize=7) ax8.xaxis.pane.fill = False ax8.yaxis.pane.fill = False ax8.zaxis.pane.fill = False ax8.xaxis.pane.set_edgecolor(colors['grid']) ax8.yaxis.pane.set_edgecolor(colors['grid']) ax8.zaxis.pane.set_edgecolor(colors['grid'])
ax9 = fig.add_subplot(3, 3, 9) style_ax(ax9, 'Prime Gap |p − q| vs Error') gaps = np.abs(p_vals - q_vals) ax9.scatter(gaps[mask0], errors[mask0], c=colors['green'], s=15, alpha=0.5, label='Error=0') ax9.scatter(gaps[mask1], errors[mask1], c=colors['red'], s=25, alpha=0.8, label='Error>0', marker='D') ax9.set_xlabel('Prime gap |p − q|') ax9.set_ylabel('Error |N − (p+q)|') ax9.legend(fontsize=8, facecolor=colors['panel'], labelcolor=colors['text'], framealpha=0.8)
plt.suptitle('Goldbach-Type Error Minimization — Full Analysis', fontsize=15, color=colors['text'], y=1.01, fontweight='bold') plt.tight_layout() plt.savefig('goldbach_error_analysis.png', dpi=150, bbox_inches='tight', facecolor=colors['bg']) plt.show() print("\nFigure saved as 'goldbach_error_analysis.png'")
|