-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathalgebraic_numbers.cpp
More file actions
3607 lines (3237 loc) · 144 KB
/
Copy pathalgebraic_numbers.cpp
File metadata and controls
3607 lines (3237 loc) · 144 KB
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*++
Copyright (c) 2011 Microsoft Corporation
Module Name:
algebraic_numbers.cpp
Abstract:
Real Algebraic Numbers
Author:
Leonardo (leonardo) 2011-11-22
Notes:
--*/
#include "util/mpbq.h"
#include "util/basic_interval.h"
#include "util/scoped_ptr_vector.h"
#include "util/mpbqi.h"
#include "util/timeit.h"
#include "util/common_msgs.h"
#include "util/index_sort_with_mutations.h"
#include "math/polynomial/algebraic_numbers.h"
#include "math/polynomial/upolynomial.h"
#include "math/polynomial/sexpr2upolynomial.h"
#include "math/polynomial/algebraic_params.hpp"
namespace algebraic_numbers {
struct basic_cell {
mpq m_value;
};
// Each algebraic number is associated with two
// isolating (refinable) intervals. The second
// interval just caches refinements of the first one.
struct algebraic_cell {
// polynomial
unsigned m_p_sz;
mpz * m_p;
mpbqi m_interval; // isolating/refinable interval
// sign of p at the lower and upper bounds of m_interval
unsigned m_minimal:1; // true if p is a minimal polynomial for representing the number
unsigned m_sign_lower:1;
unsigned m_not_rational:1; // if true we know for sure it is not a rational
unsigned m_i:29; // number is the i-th root of p, 0 if it is not known which root of p the number is.
algebraic_cell():m_p_sz(0), m_p(nullptr), m_minimal(false), m_not_rational(false), m_i(0) {}
bool is_minimal() const { return m_minimal != 0; }
};
typedef polynomial::manager poly_manager;
typedef upolynomial::manager upoly_manager;
typedef upolynomial::numeral_vector upoly;
typedef upolynomial::scoped_numeral_vector scoped_upoly;
typedef upolynomial::factors factors;
void manager::get_param_descrs(param_descrs & r) {
algebraic_params::collect_param_descrs(r);
}
struct manager::imp {
reslimit& m_limit;
manager & m_wrapper;
small_object_allocator & m_allocator;
unsynch_mpq_manager & m_qmanager;
mpbq_manager m_bqmanager;
mpbqi_manager m_bqimanager;
poly_manager m_pmanager;
upoly_manager m_upmanager;
mpq m_zero;
scoped_mpz m_is_rational_tmp;
scoped_upoly m_isolate_tmp1;
scoped_upoly m_isolate_tmp2;
scoped_upoly m_isolate_tmp3;
scoped_upoly m_eval_sign_tmp;
factors m_isolate_factors;
scoped_mpbq_vector m_isolate_roots;
scoped_mpbq_vector m_isolate_lowers;
scoped_mpbq_vector m_isolate_uppers;
scoped_upoly m_add_tmp;
polynomial::var m_x;
polynomial::var m_y;
// configuration
int m_min_magnitude;
bool m_factor;
polynomial::factor_params m_factor_params;
int m_zero_accuracy;
// statistics
unsigned m_compare_cheap;
unsigned m_compare_sturm;
unsigned m_compare_refine;
unsigned m_compare_poly_eq;
imp(reslimit& lim, manager & w, unsynch_mpq_manager & m, params_ref const & p, small_object_allocator & a):
m_limit(lim),
m_wrapper(w),
m_allocator(a),
m_qmanager(m),
m_bqmanager(m),
m_bqimanager(m_bqmanager),
m_pmanager(lim, m, &a),
m_upmanager(lim, m),
m_is_rational_tmp(m),
m_isolate_tmp1(upm()),
m_isolate_tmp2(upm()),
m_isolate_tmp3(upm()),
m_eval_sign_tmp(upm()),
m_isolate_factors(upm()),
m_isolate_roots(bqm()),
m_isolate_lowers(bqm()),
m_isolate_uppers(bqm()),
m_add_tmp(upm()) {
updt_params(p);
reset_statistics();
m_x = pm().mk_var();
m_y = pm().mk_var();
}
bool acell_inv(algebraic_cell const& c) {
auto s = upm().eval_sign_at(c.m_p_sz, c.m_p, lower(&c));
return s == sign_zero || c.m_sign_lower == (s == sign_neg);
}
void checkpoint() {
if (!m_limit.inc())
throw algebraic_exception(Z3_CANCELED_MSG);
}
void reset_statistics() {
m_compare_cheap = 0;
m_compare_sturm = 0;
m_compare_refine = 0;
m_compare_poly_eq = 0;
}
void collect_statistics(statistics & st) {
#ifndef _EXTERNAL_RELEASE
st.update("algebraic compare cheap", m_compare_cheap);
st.update("algebraic compare sturm", m_compare_sturm);
st.update("algebraic compare refine", m_compare_refine);
st.update("algebraic compare poly", m_compare_poly_eq);
#endif
}
void updt_params(params_ref const & _p) {
algebraic_params p(_p);
m_min_magnitude = -static_cast<int>(p.min_mag());
m_factor = p.factor();
m_factor_params.m_max_p = p.factor_max_prime();
m_factor_params.m_p_trials = p.factor_num_primes();
m_factor_params.m_max_search_size = p.factor_search_size();
m_zero_accuracy = -static_cast<int>(p.zero_accuracy());
}
unsynch_mpq_manager & qm() {
return m_qmanager;
}
mpbq_manager & bqm() {
return m_bqmanager;
}
mpbqi_manager & bqim() {
return m_bqimanager;
}
poly_manager & pm() {
return m_pmanager;
}
upoly_manager & upm() {
return m_upmanager;
}
void del_basic(basic_cell * c) {
qm().del(c->m_value);
m_allocator.deallocate(sizeof(basic_cell), c);
}
void del_poly(algebraic_cell * c) {
for (unsigned i = 0; i < c->m_p_sz; ++i)
qm().del(c->m_p[i]);
m_allocator.deallocate(sizeof(mpz)*c->m_p_sz, c->m_p);
c->m_p = nullptr;
c->m_p_sz = 0;
}
void del_interval(algebraic_cell * c) {
bqim().del(c->m_interval);
}
void del(algebraic_cell * c) {
del_poly(c);
del_interval(c);
m_allocator.deallocate(sizeof(algebraic_cell), c);
}
void del(numeral & a) {
if (a.is_null())
return;
if (a.is_basic())
del_basic(a.to_basic());
else
del(a.to_algebraic());
a.clear();
}
void reset(numeral & a) {
del(a);
}
bool is_zero(numeral const & a) {
return a.is_null();
}
bool is_pos(numeral const & a) {
if (a.is_basic())
return qm().is_pos(basic_value(a));
else
return bqim().is_pos(a.to_algebraic()->m_interval);
}
bool is_neg(numeral const & a) {
if (a.is_basic())
return qm().is_neg(basic_value(a));
else
return bqim().is_neg(a.to_algebraic()->m_interval);
}
mpq const & basic_value(numeral const & a) {
SASSERT(a.is_basic());
if (is_zero(a))
return m_zero;
else
return a.to_basic()->m_value;
}
bool is_int(numeral & a) {
if (a.is_basic())
return qm().is_int(basic_value(a));
if (a.to_algebraic()->m_not_rational)
return false; // we know for sure a is not a rational (and consequently an integer)
// make sure the isolating interval has at most one integer
if (!refine_until_prec(a, 1)) {
SASSERT(a.is_basic()); // a became basic
return qm().is_int(basic_value(a));
}
// Find unique integer in the isolating interval
algebraic_cell * c = a.to_algebraic();
scoped_mpz candidate(qm());
bqm().floor(qm(), upper(c), candidate);
SASSERT(bqm().ge(upper(c), candidate));
if (bqm().lt(lower(c), candidate) && upm().eval_sign_at(c->m_p_sz, c->m_p, candidate) == sign_zero) {
m_wrapper.set(a, candidate);
return true;
}
return false;
}
/*
In our representation, non-basic numbers are encoded by
polynomials of the form: a_n * x^n + ... + a_0 where
a_0 != 0.
Thus, we can find whether a non-basic number is actually a rational
by using the Rational root theorem.
p/q is a root of a_n * x^n + ... + a_0
If p is a factor of a_0, and q is a factor of a_n.
If the isolating interval (lower, upper) has size less than 1/a_n, then
(a_n*lower, a_n*upper) contains at most one integer.
Let u be this integer, then the non-basic number is a rational iff
u/a_n is the actual root.
*/
bool is_rational(numeral & a) {
if (a.is_basic())
return true;
if (a.to_algebraic()->m_not_rational)
return false; // we know for sure a is not a rational
TRACE(algebraic_bug, tout << "is_rational(a):\n"; display_root(tout, a); tout << "\n"; display_interval(tout, a); tout << "\n";);
algebraic_cell * c = a.to_algebraic();
save_intervals saved_a(*this, a);
mpz & a_n = c->m_p[c->m_p_sz - 1];
scoped_mpz & abs_a_n = m_is_rational_tmp;
qm().set(abs_a_n, a_n);
qm().abs(abs_a_n);
// 1/2^{log2(a_n)+1} <= 1/a_n
unsigned k = qm().log2(abs_a_n);
k++;
TRACE(algebraic_bug, tout << "abs(an): " << qm().to_string(abs_a_n) << ", k: " << k << "\n";);
// make sure the isolating interval size is less than 1/2^k
if (!refine_until_prec(a, k)) {
SASSERT(a.is_basic()); // a became basic
return true;
}
TRACE(algebraic_bug, tout << "interval after refinement: "; display_interval(tout, a); tout << "\n";);
// Find unique candidate rational in the isolating interval
scoped_mpbq a_n_lower(bqm());
scoped_mpbq a_n_upper(bqm());
bqm().mul(lower(c), abs_a_n, a_n_lower);
bqm().mul(upper(c), abs_a_n, a_n_upper);
scoped_mpz zcandidate(qm());
bqm().floor(qm(), a_n_upper, zcandidate);
scoped_mpq candidate(qm());
qm().set(candidate, zcandidate, abs_a_n);
SASSERT(bqm().ge(upper(c), candidate));
// Find if candidate is an actual root
if (bqm().lt(lower(c), candidate) && upm().eval_sign_at(c->m_p_sz, c->m_p, candidate) == sign_zero) {
saved_a.restore_if_too_small();
set(a, candidate);
return true;
}
else {
saved_a.restore_if_too_small();
c->m_not_rational = true;
return false;
}
}
void to_rational(numeral & a, mpq & r) {
VERIFY(is_rational(a));
SASSERT(a.is_basic());
qm().set(r, basic_value(a));
}
void to_rational(numeral & a, rational & r) {
scoped_mpq tmp(qm());
to_rational(a, tmp);
rational tmp2(tmp);
r = tmp2;
}
unsigned degree(numeral const & a) {
if (is_zero(a))
return 0;
if (a.is_basic())
return 1;
return a.to_algebraic()->m_p_sz - 1;
}
void swap(numeral & a, numeral & b) noexcept {
a.swap(b);
}
basic_cell * mk_basic_cell(mpq & n) {
if (qm().is_zero(n))
return nullptr;
void * mem = static_cast<basic_cell*>(m_allocator.allocate(sizeof(basic_cell)));
basic_cell * c = new (mem) basic_cell();
qm().swap(c->m_value, n);
return c;
}
sign sign_lower(algebraic_cell * c) const {
return c->m_sign_lower == 0 ? sign_pos : sign_neg;
}
mpbq const & lower(algebraic_cell const * c) const { return c->m_interval.lower(); }
mpbq const & upper(algebraic_cell const * c) const { return c->m_interval.upper(); }
mpbq & lower(algebraic_cell * c) { return c->m_interval.lower(); }
mpbq & upper(algebraic_cell * c) { return c->m_interval.upper(); }
void update_sign_lower(algebraic_cell * c) {
sign sl = upm().eval_sign_at(c->m_p_sz, c->m_p, lower(c));
// The isolating intervals are refinable. Thus, the polynomial has opposite signs at lower and upper.
SASSERT(sl != sign_zero);
SASSERT(upm().eval_sign_at(c->m_p_sz, c->m_p, upper(c)) == -sl);
c->m_sign_lower = sl == sign_neg;
SASSERT(acell_inv(*c));
}
// Make sure the GCD of the coefficients is one and the leading coefficient is positive
void normalize_coeffs(algebraic_cell * c) {
SASSERT(c->m_p_sz > 2);
upm().normalize(c->m_p_sz, c->m_p);
if (upm().m().is_neg(c->m_p[c->m_p_sz-1])) {
upm().neg(c->m_p_sz, c->m_p);
c->m_sign_lower = !(c->m_sign_lower);
SASSERT(acell_inv(*c));
}
}
algebraic_cell * mk_algebraic_cell(unsigned sz, mpz const * p, mpbq const & lower, mpbq const & upper, bool minimal) {
SASSERT(sz > 2);
void * mem = static_cast<algebraic_cell*>(m_allocator.allocate(sizeof(algebraic_cell)));
algebraic_cell * c = new (mem) algebraic_cell();
c->m_p_sz = sz;
c->m_p = static_cast<mpz*>(m_allocator.allocate(sizeof(mpz)*sz));
for (unsigned i = 0; i < sz; ++i) {
new (c->m_p + i) mpz();
qm().set(c->m_p[i], p[i]);
}
bqim().set(c->m_interval, lower, upper);
update_sign_lower(c);
c->m_minimal = minimal;
SASSERT(c->m_i == 0);
SASSERT(c->m_not_rational == false);
if (c->m_minimal)
c->m_not_rational = true;
normalize_coeffs(c);
return c;
}
void set(numeral & a, mpq & n) {
if (qm().is_zero(n)) {
reset(a);
SASSERT(is_zero(a));
return;
}
if (a.is_basic()) {
if (is_zero(a))
a = mk_basic_cell(n);
else
qm().set(a.to_basic()->m_value, n);
}
else {
del(a);
a = mk_basic_cell(n);
}
}
void set(numeral & a, mpq const & n) {
scoped_mpq tmp(qm());
qm().set(tmp, n);
set(a, tmp);
}
void copy_poly(algebraic_cell * c, unsigned sz, mpz const * p) {
SASSERT(c->m_p == nullptr);
SASSERT(c->m_p_sz == 0);
c->m_p_sz = sz;
c->m_p = static_cast<mpz*>(m_allocator.allocate(sizeof(mpz)*sz));
for (unsigned i = 0; i < sz; ++i) {
new (c->m_p + i) mpz();
qm().set(c->m_p[i], p[i]);
}
}
void set_interval(algebraic_cell * c, mpbqi const & i) {
bqim().set(c->m_interval, i);
}
void set_interval(algebraic_cell * c, mpbq const & l, mpbq const & u) {
bqim().set(c->m_interval, l, u);
}
// Copy fields from source to target.
// It assumes that fields target->m_p is NULL or was deleted.
void copy(algebraic_cell * target, algebraic_cell const * source) {
copy_poly(target, source->m_p_sz, source->m_p);
set_interval(target, source->m_interval);
target->m_minimal = source->m_minimal;
target->m_sign_lower = source->m_sign_lower;
target->m_not_rational = source->m_not_rational;
target->m_i = source->m_i;
//SASSERT(acell_inv(*source)); source could be owned by a different manager
SASSERT(acell_inv(*target));
}
void set(numeral & a, unsigned sz, mpz const * p, mpbq const & lower, mpbq const & upper, bool minimal) {
SASSERT(sz > 1);
if (sz == 2) {
// it is linear
scoped_mpq tmp(qm());
qm().set(tmp, p[0], p[1]);
qm().neg(tmp);
set(a, tmp);
}
else {
if (a.is_basic()) {
del(a);
a = mk_algebraic_cell(sz, p, lower, upper, minimal);
}
else {
SASSERT(sz > 2);
algebraic_cell * c = a.to_algebraic();
del_poly(c);
copy_poly(c, sz, p);
set_interval(c, lower, upper);
c->m_minimal = minimal;
c->m_not_rational = false;
if (c->m_minimal)
c->m_not_rational = true;
c->m_i = 0;
update_sign_lower(c);
normalize_coeffs(c);
}
SASSERT(acell_inv(*a.to_algebraic()));
}
TRACE(algebraic, tout << "a: "; display_root(tout, a); tout << "\n";);
}
void set(numeral & a, numeral const & b) {
if (&a == &b)
return;
if (a.is_basic()) {
if (b.is_basic()) {
SASSERT(a.is_basic() && b.is_basic());
set(a, basic_value(b));
}
else {
SASSERT(a.is_basic() && !b.is_basic());
del(a);
void * mem = m_allocator.allocate(sizeof(algebraic_cell));
algebraic_cell * c = new (mem) algebraic_cell();
a = c;
copy(c, b.to_algebraic());
SASSERT(acell_inv(*c));
}
}
else {
if (b.is_basic()) {
SASSERT(!a.is_basic() && b.is_basic());
del(a);
set(a, basic_value(b));
}
else {
SASSERT(!a.is_basic() && !b.is_basic());
del_poly(a.to_algebraic());
del_interval(a.to_algebraic());
copy(a.to_algebraic(), b.to_algebraic());
SASSERT(acell_inv(*a.to_algebraic()));
}
}
}
bool factor(scoped_upoly const & up, factors & r) {
if (m_factor) {
return upm().factor(up, r, m_factor_params);
}
else {
scoped_upoly & up_sqf = m_isolate_tmp3;
up_sqf.reset();
upm().square_free(up.size(), up.data(), up_sqf);
TRACE(algebraic, upm().display(tout, up_sqf.size(), up_sqf.data()); tout << "\n";);
r.push_back(up_sqf, 1);
return false;
}
}
struct lt_proc {
manager & m;
lt_proc(manager & _m):m(_m) {}
bool operator()(numeral const & a1, numeral const & a2) const {
return m.lt(a1, a2);
}
};
void check_transitivity(numeral_vector& r) {
lt_proc lt(m_wrapper);
for (unsigned i = 0; i < r.size(); ++i) {
auto& a = r[i];
for (unsigned j = 0; j < r.size(); ++j) {
auto& b = r[j];
for (unsigned k = 0; k < r.size(); ++k) {
auto& c = r[k];
bool b_lt_a = lt(b, a);
bool c_lt_b = lt(c, b);
bool c_lt_a = lt(c, a);
(void)b_lt_a;
(void)c_lt_b;
(void)c_lt_a;
// (a <= b & b <= c) => a <= c
// b < a or c < b or !(c < a)
CTRACE(algebraic_bug,
(!b_lt_a && !c_lt_b && c_lt_a),
display_root(tout << "a ", a) << "\n";
display_root(tout << "b ", b) << "\n";
display_root(tout << "c ", c) << "\n";);
SASSERT(b_lt_a || c_lt_b || !c_lt_a);
}
}
}
}
// Sort an index permutation with a bounds-safe, mutation-aware merge
// sort. The comparator (compare/lt) is NOT pure: it MUTATES the
// algebraic numbers it compares (refining their isolating intervals) and
// may throw on the resource limit, so std::sort would be undefined
// behavior here. See util/index_sort_with_mutations.h for the rationale.
void merge_sort_roots_perm(numeral_vector & r, unsigned_vector & perm) {
unsigned n = perm.size();
if (n < 2)
return;
unsigned_vector scratch;
scratch.resize(n, 0);
// Strict, total, stable index comparator: decided sign first, then index
// tiebreak (covers the equal/limit case so the order stays deterministic).
auto idx_lt = [&](unsigned x, unsigned y) {
::sign s = compare(r[x], r[y]);
return s != sign_zero ? s == sign_neg : x < y;
};
stable_index_merge_sort(perm.data(), scratch.data(), n, idx_lt);
}
void sort_roots(numeral_vector & r) {
if (!m_limit.inc())
return;
// DEBUG_CODE(check_transitivity(r););
unsigned n = r.size();
if (n < 2)
return;
unsigned_vector perm;
perm.resize(n, 0);
for (unsigned i = 0; i < n; ++i)
perm[i] = i;
merge_sort_roots_perm(r, perm);
// Apply the permutation in place via swap cycles. anum swap is a cheap
// pointer swap (move nulls the source), so this is O(n) cheap moves.
unsigned_vector pos; // pos[v] = current position of element v
pos.resize(n, 0);
unsigned_vector at; // at[p] = element currently at position p
at.resize(n, 0);
for (unsigned i = 0; i < n; ++i) {
pos[i] = i;
at[i] = i;
}
for (unsigned target = 0; target < n; ++target) {
unsigned want = perm[target]; // element that should end up at target
unsigned cur = pos[want]; // where it currently is
if (cur == target)
continue;
unsigned other = at[target]; // element currently at target
std::swap(r[target], r[cur]);
at[target] = want; at[cur] = other;
pos[want] = target; pos[other] = cur;
}
}
void isolate_roots(scoped_upoly const & up, numeral_vector & roots) {
TRACE(algebraic, upm().display(tout, up); tout << "\n";);
if (up.empty())
return; // ignore the zero polynomial
factors & fs = m_isolate_factors;
fs.reset();
bool full_fact;
if (upm().has_zero_roots(up.size(), up.data())) {
roots.push_back(numeral());
scoped_upoly & nz_up = m_isolate_tmp2;
upm().remove_zero_roots(up.size(), up.data(), nz_up);
full_fact = factor(nz_up, fs);
}
else {
full_fact = factor(up, fs);
}
unsigned num_factors = fs.distinct_factors();
for (unsigned i = 0; i < num_factors; ++i) {
upolynomial::numeral_vector const & f = fs[i];
// polynomial f contains the non zero roots
unsigned d = upm().degree(f);
TRACE(algebraic, tout << "factor " << i << " degree: " << d << "\n";);
if (d == 0)
continue; // found all roots of f
scoped_mpq r(qm());
if (d == 1) {
TRACE(algebraic, tout << "linear polynomial...\n";);
// f is a linear polynomial ax + b
// set r <- -b/a
qm().set(r, f[0]);
qm().div(r, f[1], r);
qm().neg(r);
roots.push_back(numeral(mk_basic_cell(r)));
continue;
}
SASSERT(m_isolate_roots.empty() && m_isolate_lowers.empty() && m_isolate_uppers.empty());
upm().sqf_isolate_roots(f.size(), f.data(), bqm(), m_isolate_roots, m_isolate_lowers, m_isolate_uppers);
// collect rational/basic roots
unsigned sz = m_isolate_roots.size();
TRACE(algebraic, tout << "isolated roots: " << sz << "\n";);
for (unsigned i = 0; i < sz; ++i) {
to_mpq(qm(), m_isolate_roots[i], r);
roots.push_back(numeral(mk_basic_cell(r)));
}
SASSERT(m_isolate_uppers.size() == m_isolate_lowers.size());
// collect non-basic roots
sz = m_isolate_lowers.size();
for (unsigned i = 0; i < sz; ++i) {
mpbq & lower = m_isolate_lowers[i];
mpbq & upper = m_isolate_uppers[i];
if (!upm().isolating2refinable(f.size(), f.data(), bqm(), lower, upper)) {
// found rational root... it is stored in lower
to_mpq(qm(), lower, r);
roots.push_back(numeral(mk_basic_cell(r)));
}
else {
algebraic_cell * c = mk_algebraic_cell(f.size(), f.data(), lower, upper, full_fact);
roots.push_back(numeral(c));
}
}
m_isolate_roots.reset();
m_isolate_lowers.reset();
m_isolate_uppers.reset();
}
sort_roots(roots);
}
void isolate_roots(polynomial_ref const & p, numeral_vector & roots) {
SASSERT(is_univariate(p));
TRACE(algebraic, tout << "isolating roots of: " << p << "\n";);
if (::is_zero(p))
return; // ignore the zero polynomial
scoped_upoly & up = m_isolate_tmp1;
upm().to_numeral_vector(p, up);
isolate_roots(up, roots);
}
unsigned sign_variations_at_mpq(upolynomial::upolynomial_sequence const & seq, mpq const & b) {
unsigned sz = seq.size();
if (sz <= 1)
return 0;
unsigned r = 0;
int sign = 0, prev_sign = 0;
for (unsigned i = 0; i < sz; ++i) {
unsigned psz = seq.size(i);
mpz const * p = seq.coeffs(i);
sign = static_cast<int>(upm().eval_sign_at(psz, p, b));
if (sign == 0)
continue;
if (prev_sign != 0 && sign != prev_sign)
r++;
prev_sign = sign;
}
return r;
}
// Isolate the i-th real root of sqf_p (1-based), where sqf_p is square-free and univariate.
// Return the root as an algebraic number in r. The polynomial stored in the result is sqf_p.
void isolate_kth_root(scoped_upoly const & sqf_p, upolynomial::upolynomial_sequence const & seq, unsigned i, numeral & r) {
SASSERT(i > 0);
unsigned sz = sqf_p.size();
mpz const * p = sqf_p.data();
SASSERT(sz > 0);
if (sz == 2) {
// Linear polynomial ax + b: root is -b/a (always rational).
scoped_mpq q(qm());
qm().set(q, p[0], p[1]);
qm().neg(q);
set(r, q);
return;
}
unsigned pos_k = upm().knuth_positive_root_upper_bound(sz, p);
unsigned neg_k = upm().knuth_negative_root_upper_bound(sz, p);
scoped_mpbq lo(bqm()), hi(bqm()), mid(bqm());
unsigned vminus = upm().sign_variations_at_minus_inf(seq);
unsigned v0 = upm().sign_variations_at_zero(seq);
unsigned vplus = upm().sign_variations_at_plus_inf(seq);
unsigned le0_cnt = vminus - v0; // roots in (-oo, 0]
unsigned vlo, vhi;
unsigned target;
if (i <= le0_cnt) {
// Isolate within (-2^neg_k, 0] to keep the interval on the non-positive side.
bqm().power(mpbq(2), neg_k, lo);
bqm().neg(lo);
bqm().set(hi, 0);
vlo = vminus;
vhi = v0;
target = i;
}
else {
// Isolate within (0, 2^pos_k] to keep the interval on the non-negative side.
bqm().set(lo, 0);
bqm().power(mpbq(2), pos_k, hi);
vlo = v0;
vhi = vplus;
target = i - le0_cnt;
}
// Sanity: sqf_p has at least i roots.
SASSERT(vlo >= vhi);
SASSERT(i <= vminus - vplus);
SASSERT(target > 0);
SASSERT(target <= vlo - vhi);
while (vlo > vhi + 1) {
checkpoint();
bqm().add(lo, hi, mid);
bqm().div2(mid);
unsigned vmid = upm().sign_variations_at(seq, mid);
unsigned left_cnt = vlo - vmid; // roots in (lo, mid]
if (target <= left_cnt) {
bqm().set(hi, mid);
vhi = vmid;
}
else {
bqm().set(lo, mid);
vlo = vmid;
target -= left_cnt;
}
}
SASSERT(vlo == vhi + 1);
// If the upper endpoint is exactly a dyadic root, return it as a basic number.
if (upm().eval_sign_at(sz, p, hi) == 0) {
scoped_mpq q(qm());
to_mpq(qm(), hi, q);
set(r, q);
return;
}
// Convert the isolating interval into a refinable one (or discover a dyadic root on the way).
scoped_mpbq a(bqm()), b(bqm());
bqm().set(a, lo);
bqm().set(b, hi);
if (!upm().isolating2refinable(sz, p, bqm(), a, b)) {
scoped_mpq q(qm());
to_mpq(qm(), a, q);
set(r, q);
return;
}
// At this point [a, b] is an *isolating* and *refinable* interval for p:
// it contains exactly one real root of the square-free polynomial p, and
// neither endpoint is itself that root. That root could still be a
// *rational* number: unlike the general isolate_roots(), this closest-root
// path does NOT factor p, so a reducible polynomial (e.g. a product of
// linear factors) is handled whole and keeps its rational roots instead of
// exposing them as degree-1 factors. If we blindly built an algebraic_cell
// here we would create a "root object" that is really just a rational, which
// is both wasteful and, downstream, error-prone (algebraic-number comparison
// must special-case such cells). So first try to recognize a rational root
// and, if found, return it as a plain rational (basic numeral).
if (rational_root_in_interval(sz, p, a, b, r))
return;
del(r);
r = mk_algebraic_cell(sz, p, a, b, false /* minimal */);
SASSERT(acell_inv(*r.to_algebraic()));
}
// Decide whether the unique real root of the square-free integer polynomial p
// that lies in the isolating interval [l, u] is a rational number and, if so,
// store it in r as a basic (rational) numeral and return true. Otherwise return
// false (the root is irrational and must be represented as a root object).
//
// Notation: p(x) = a_n*x^n + ... + a_1*x + a_0 with a_i integers (mpz), a_n != 0.
// mpbq = dyadic rational (denominator is a power of two);
// mpq = arbitrary rational; mpz = integer.
//
// Preconditions (guaranteed by the caller, isolate_kth_root):
// * p is square-free, so all its roots are simple (no repeated roots).
// * [l, u] is an isolating interval: it contains EXACTLY ONE real root of p.
// This is why we may speak of "the root" in the interval.
//
// The mathematics used:
//
// 1. Rational Root Theorem. If a polynomial with integer coefficients has a
// rational root num/den, where den > 0 does not divide num,
// then den divides the leading coefficient a_n. In
// particular every rational root can be written with denominator |a_n|,
// i.e. as m/|a_n| for some integer m. We can represent the root as that m/|a_n|
// for some integer m.
//
// 2. Two distinct rationals m1/|a_n| and m2/|a_n| differ by at least 1/|a_n|. Hence if we
// first shrink [l, u] to have width < 1/|a_n|, the interval can contain at
// most one rational of the form m/|a_n| => if the
// root is rational it must equal that single candidate.
bool rational_root_in_interval(unsigned sz, mpz const * p, mpbq & l, mpbq & u, numeral & r) {
// a_n is the leading coefficient; work with its absolute value |a_n|.
mpz const & a_n = p[sz - 1];
scoped_mpz abs_a_n(qm());
qm().set(abs_a_n, a_n);
qm().abs(abs_a_n);
// We need the interval width to be strictly less than 1/|a_n|
// refine() shrinks by halving, i.e. it reaches width <= 1/2^k. Choosing
// k = floor(log2(|a_n|)) + 1
// gives 2^k > |a_n|, hence 1/2^k < 1/|a_n|, which is what we want.
unsigned k = qm().log2(abs_a_n);
k++;
// Refine [l, u] to precision k. refine() returns false in the lucky case
// where the bisection lands *exactly* on a dyadic rational that is a root
// of p; in that case the exact root has been stored in the lower endpoint l,
// so we can return it directly as a basic rational.
if (!upm().refine(sz, p, bqm(), l, u, k)) {
scoped_mpq q(qm());
to_mpq(qm(), l, q);
set(r, q);
return true;
}
// Otherwise refine() succeeded and [l, u] now has width < 1/|a_n|.
// Build the unique candidate rational m/|a_n| that could lie in [l, u].
// Scale the interval by |a_n|: [l*|a_n|, u*|a_n|] has width < 1, so it
// contains at most one integer. That integer, if any, is m = floor(u*|a_n|),
// and the candidate rational is m/|a_n|.
scoped_mpbq a_n_upper(bqm());
bqm().mul(u, abs_a_n, a_n_upper); // a_n_upper = u * |a_n|
scoped_mpz zcandidate(qm());
bqm().floor(qm(), a_n_upper, zcandidate); // m = floor(u * |a_n|)
scoped_mpq candidate(qm());
qm().set(candidate, zcandidate, abs_a_n); // candidate = m / |a_n|
// By construction candidate <= u. We still must confirm two things:
// (a) candidate is actually inside the interval, i.e. l < candidate
// (if candidate <= l then there is no rational m/|a_n| inside [l,u]);
// (b) candidate is genuinely a root, i.e. p(candidate) == 0.
// If both hold, then since the interval isolates exactly one root, that
// root equals candidate and is rational. If p(candidate) != 0, then by the
// Rational Root Theorem no rational (which would have to be m/|a_n|) is a
// root here, so the single root in the interval is irrational.
if (bqm().lt(l, candidate) && upm().eval_sign_at(sz, p, candidate) == sign_zero) {
set(r, candidate);
return true;
}
return false;
}
// Closest-root isolation for an (integer) univariate polynomial.
void isolate_roots_closest_univariate(polynomial_ref const & p, mpq const & s, numeral_vector & roots, svector<unsigned> & indices) {
SASSERT(is_univariate(p));
SASSERT(roots.empty());
indices.reset();
if (::is_zero(p) || ::is_const(p))
return;
// Convert to dense univariate form and take the square-free part.
scoped_upoly & up = m_isolate_tmp1;
scoped_upoly & sqf_p = m_isolate_tmp3;
up.reset();
sqf_p.reset();
upm().to_numeral_vector(p, up);
if (up.empty())
return;
upm().square_free(up.size(), up.data(), sqf_p);
if (sqf_p.empty() || upm().degree(sqf_p) == 0)
return;
upolynomial::scoped_upolynomial_sequence seq(upm());
upm().sturm_seq(sqf_p.size(), sqf_p.data(), seq);
unsigned vminus = upm().sign_variations_at_minus_inf(seq);
unsigned vplus = upm().sign_variations_at_plus_inf(seq);
if (vminus <= vplus)
return;
unsigned vs = sign_variations_at_mpq(seq, s);
unsigned total = vminus - vplus;
unsigned k = vminus - vs; // #roots in (-oo, s]
if (upm().eval_sign_at(sqf_p.size(), sqf_p.data(), s) == 0) {
roots.push_back(numeral());
set(roots.back(), s);
indices.push_back(k);
return;
}
// predecessor (<= s)
if (k > 0) {
roots.push_back(numeral());
isolate_kth_root(sqf_p, seq, k, roots.back());
indices.push_back(k);
}
// successor (> s)
if (k < total) {
roots.push_back(numeral());
isolate_kth_root(sqf_p, seq, k + 1, roots.back());
indices.push_back(k + 1);
}
}
void mk_root(scoped_upoly const & up, unsigned i, numeral & r) {
// TODO: implement version that finds i-th root without isolating all roots.
if (i == 0)
throw algebraic_exception("invalid root object, root index must be greater than 0");
if (up.empty())
throw algebraic_exception("invalid root object, polynomial must not be the zero polynomial");
SASSERT(i != 0);
scoped_numeral_vector roots(m_wrapper);
isolate_roots(up, roots);
unsigned num_roots = roots.size();
TRACE(algebraic, tout << "num-roots: " << num_roots << "\n";
for (unsigned i = 0; i < num_roots; ++i) {
display_interval(tout, roots[i]);
tout << "\n";
});
if (i > num_roots)