Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

""" 

Other functions 

 

TESTS: 

 

Check that gamma function imports are deprecated (:trac:`24411`):: 

 

sage: from sage.functions.other import beta 

sage: beta(x, x) 

doctest:...: DeprecationWarning: 

Importing beta from here is deprecated. If you need to use it, please import it directly from sage.functions.gamma 

See http://trac.sagemath.org/24411 for details. 

beta(x, x) 

""" 

from __future__ import print_function 

from six.moves import range 

from six import integer_types 

 

from sage.misc.lazy_import import lazy_import 

lazy_import('sage.functions.gamma', 

('gamma', 'log_gamma', 'gamma_inc', 'incomplete_gamma', 

'gamma_inc_lower', 'psi', 'beta'), deprecation=24411) 

 

from sage.symbolic.function import GinacFunction, BuiltinFunction 

from sage.symbolic.expression import Expression 

from sage.libs.pynac.pynac import (register_symbol, symbol_table, 

py_factorial_py, I) 

from sage.symbolic.all import SR 

from sage.rings.all import Integer, Rational, RealField, ZZ, ComplexField 

from sage.rings.complex_number import is_ComplexNumber 

from sage.misc.latex import latex 

from sage.misc.decorators import rename_keyword 

import math 

 

from sage.structure.element import coercion_model 

 

# avoid name conflicts with `parent` as a function parameter 

from sage.structure.all import parent as s_parent 

 

from sage.symbolic.constants import pi 

from sage.functions.log import exp 

from sage.functions.trig import arctan2 

from sage.functions.exp_integral import Ei 

from sage.libs.mpmath import utils as mpmath_utils 

from sage.arith.all import binomial as arith_binomial 

 

one_half = SR.one() / SR(2) 

 

 

class Function_abs(GinacFunction): 

def __init__(self): 

r""" 

The absolute value function. 

 

EXAMPLES:: 

 

sage: var('x y') 

(x, y) 

sage: abs(x) 

abs(x) 

sage: abs(x^2 + y^2) 

abs(x^2 + y^2) 

sage: abs(-2) 

2 

sage: sqrt(x^2) 

sqrt(x^2) 

sage: abs(sqrt(x)) 

sqrt(abs(x)) 

sage: complex(abs(3*I)) 

(3+0j) 

 

sage: f = sage.functions.other.Function_abs() 

sage: latex(f) 

\mathrm{abs} 

sage: latex(abs(x)) 

{\left| x \right|} 

sage: abs(x)._sympy_() 

Abs(x) 

 

Test pickling:: 

 

sage: loads(dumps(abs(x))) 

abs(x) 

 

TESTS: 

 

Check that :trac:`12588` is fixed:: 

 

sage: abs(pi*I) 

pi 

sage: abs(pi*I*catalan) 

catalan*pi 

sage: abs(pi*catalan*x) 

catalan*pi*abs(x) 

sage: abs(pi*I*catalan*x) 

catalan*pi*abs(x) 

sage: abs(1.0j*pi) 

1.00000000000000*pi 

sage: abs(I*x) 

abs(x) 

sage: abs(I*pi) 

pi 

sage: abs(I*log(2)) 

log(2) 

sage: abs(I*e^5) 

e^5 

sage: abs(log(1/2)) 

-log(1/2) 

sage: abs(log(3/2)) 

log(3/2) 

sage: abs(log(1/2)*log(1/3)) 

log(1/2)*log(1/3) 

sage: abs(log(1/2)*log(1/3)*log(1/4)) 

-log(1/2)*log(1/3)*log(1/4) 

sage: abs(log(1/2)*log(1/3)*log(1/4)*i) 

-log(1/2)*log(1/3)*log(1/4) 

sage: abs(log(x)) 

abs(log(x)) 

sage: abs(zeta(I)) 

abs(zeta(I)) 

sage: abs(e^2*x) 

abs(x)*e^2 

sage: abs((pi+e)*x) 

(pi + e)*abs(x) 

""" 

GinacFunction.__init__(self, "abs", latex_name=r"\mathrm{abs}", 

conversions=dict(sympy='Abs', 

mathematica='Abs', 

giac='abs')) 

 

abs = abs_symbolic = Function_abs() 

 

 

@rename_keyword(deprecation=22079, maximum_bits="bits") 

def _eval_floor_ceil(self, x, method, bits=0, **kwds): 

""" 

Helper function to compute ``floor(x)`` or ``ceil(x)``. 

 

INPUT: 

 

- ``x`` -- a number 

 

- ``method`` -- should be either ``"floor"`` or ``"ceil"`` 

 

- ``bits`` -- how many bits to use before giving up 

 

See :class:`Function_floor` and :class:`Function_ceil` for examples 

and tests. 

 

TESTS:: 

 

sage: numbers = [SR(10^100 + exp(-100)), SR(10^100 - exp(-100)), SR(10^100)] 

sage: numbers += [-n for n in numbers] 

sage: for n in numbers: 

....: f = floor(n) 

....: c = ceil(n) 

....: if f == c: 

....: assert n in ZZ 

....: else: 

....: assert f + 1 == c 

 

A test from :trac:`12121`:: 

 

sage: e1 = pi - continued_fraction(pi).convergent(2785) 

sage: e2 = e - continued_fraction(e).convergent(1500) 

sage: f = e1/e2 

sage: f = 1 / (f - continued_fraction(f).convergent(1000)) 

sage: f = f - continued_fraction(f).convergent(1) 

sage: floor(f, bits=10000) 

-1 

sage: ceil(f, bits=10000) 

0 

 

These don't work but fail gracefully:: 

 

sage: ceil(Infinity) 

Traceback (most recent call last): 

... 

ValueError: Calling ceil() on infinity or NaN 

sage: ceil(NaN) 

Traceback (most recent call last): 

... 

ValueError: Calling ceil() on infinity or NaN 

 

TESTS:: 

 

sage: floor(pi, maximum_bits=0) 

doctest:...: DeprecationWarning: use the option 'bits' instead of 'maximum_bits' 

See http://trac.sagemath.org/22079 for details. 

3 

""" 

# First, some obvious things... 

try: 

m = getattr(x, method) 

except AttributeError: 

pass 

else: 

return m() 

 

if isinstance(x, integer_types): 

return Integer(x) 

if isinstance(x, (float, complex)): 

m = getattr(math, method) 

return Integer(m(x)) 

if type(x).__module__ == 'numpy': 

import numpy 

m = getattr(numpy, method) 

return m(x) 

 

# The strategy is to convert the number to an interval field and 

# hope that this interval will have a unique floor/ceiling. 

# 

# There are 2 reasons why this could fail: 

# (A) The expression is very complicated and we simply require 

# more bits. 

# (B) The expression is a non-obvious exact integer. In this 

# case, adding bits will not help since an interval around 

# an integer will not have a unique floor/ceiling, no matter 

# how many bits are used. 

# 

# The strategy is to first reduce the absolute diameter of the 

# interval until its size is at most 10^(-6). Then we check for 

# (B) by simplifying the expression. 

from sage.rings.all import RealIntervalField 

 

# Might it be needed to simplify x? This only applies for 

# elements of SR. 

need_to_simplify = (s_parent(x) is SR) 

 

# An integer which is close to x. We use this to increase precision 

# by subtracting this guess before converting to an interval field. 

# This mostly helps with the case that x is close to, but not equal 

# to, an exact integer. 

guess = Integer(0) 

 

# We do not use the target number of bits immediately, we just use 

# it as indication of when to stop. 

target_bits = bits 

bits = 32 

attempts = 5 

while attempts: 

attempts -= 1 

if not attempts and bits < target_bits: 

# Add one more attempt as long as the precision is less 

# than requested 

attempts = 1 

 

RIF = RealIntervalField(bits) 

if guess: 

y = x - guess 

else: 

y = x 

try: 

y_interval = RIF(y) 

except TypeError: 

# If we cannot compute a numerical enclosure, leave the 

# expression unevaluated. 

return BuiltinFunction.__call__(self, SR(x)) 

diam = y_interval.absolute_diameter() 

if diam.is_infinity(): 

# We have a very bad approximation => increase the number 

# of bits a lot 

bits *= 4 

continue 

fdiam = float(diam) 

if fdiam >= 1.0: 

# Increase number of bits to get to a diameter less than 

# 2^(-32), assuming that the diameter scales as 2^(-bits) 

bits += 32 + int(diam.log2()) 

continue 

 

# Compute ceil/floor of both ends of the interval: 

# if these match, we are done! 

a = getattr(y_interval.lower(), method)() 

b = getattr(y_interval.upper(), method)() 

if a == b: 

return a + guess 

 

# Compute a better guess for the next attempt. Since diam < 1, 

# there is a unique integer in our interval. This integer equals 

# the ceil of the lower bound and the floor of the upper bound. 

if self is floor: 

guess += b 

else: 

assert self is ceil 

guess += a 

 

if need_to_simplify and fdiam <= 1e-6: 

x = x.full_simplify().canonicalize_radical() 

need_to_simplify = False 

continue 

 

bits *= 2 

 

raise ValueError("cannot compute {}({!r}) using {} bits of precision".format(method, x, RIF.precision())) 

 

 

class Function_ceil(BuiltinFunction): 

def __init__(self): 

r""" 

The ceiling function. 

 

The ceiling of `x` is computed in the following manner. 

 

 

#. The ``x.ceil()`` method is called and returned if it 

is there. If it is not, then Sage checks if `x` is one of 

Python's native numeric data types. If so, then it calls and 

returns ``Integer(math.ceil(x))``. 

 

#. Sage tries to convert `x` into a 

``RealIntervalField`` with 53 bits of precision. Next, 

the ceilings of the endpoints are computed. If they are the same, 

then that value is returned. Otherwise, the precision of the 

``RealIntervalField`` is increased until they do match 

up or it reaches ``bits`` of precision. 

 

#. If none of the above work, Sage returns a 

``Expression`` object. 

 

 

EXAMPLES:: 

 

sage: a = ceil(2/5 + x) 

sage: a 

ceil(x + 2/5) 

sage: a(x=4) 

5 

sage: a(x=4.0) 

5 

sage: ZZ(a(x=3)) 

4 

sage: a = ceil(x^3 + x + 5/2); a 

ceil(x^3 + x + 5/2) 

sage: a.simplify() 

ceil(x^3 + x + 1/2) + 2 

sage: a(x=2) 

13 

 

:: 

 

sage: ceil(sin(8)/sin(2)) 

2 

 

:: 

 

sage: ceil(5.4) 

6 

sage: type(ceil(5.4)) 

<type 'sage.rings.integer.Integer'> 

 

:: 

 

sage: ceil(factorial(50)/exp(1)) 

11188719610782480504630258070757734324011354208865721592720336801 

sage: ceil(SR(10^50 + 10^(-50))) 

100000000000000000000000000000000000000000000000001 

sage: ceil(SR(10^50 - 10^(-50))) 

100000000000000000000000000000000000000000000000000 

 

Small numbers which are extremely close to an integer are hard to 

deal with:: 

 

sage: ceil((33^100 + 1)^(1/100)) 

Traceback (most recent call last): 

... 

ValueError: cannot compute ceil(...) using 256 bits of precision 

 

This can be fixed by giving a sufficiently large ``bits`` argument:: 

 

sage: ceil((33^100 + 1)^(1/100), bits=500) 

Traceback (most recent call last): 

... 

ValueError: cannot compute ceil(...) using 512 bits of precision 

sage: ceil((33^100 + 1)^(1/100), bits=1000) 

34 

 

:: 

 

sage: ceil(sec(e)) 

-1 

 

sage: latex(ceil(x)) 

\left \lceil x \right \rceil 

sage: ceil(x)._sympy_() 

ceiling(x) 

 

:: 

 

sage: import numpy 

sage: a = numpy.linspace(0,2,6) 

sage: ceil(a) 

array([ 0., 1., 1., 2., 2., 2.]) 

 

Test pickling:: 

 

sage: loads(dumps(ceil)) 

ceil 

""" 

BuiltinFunction.__init__(self, "ceil", 

conversions=dict(maxima='ceiling', 

sympy='ceiling', 

giac='ceil')) 

 

def _print_latex_(self, x): 

r""" 

EXAMPLES:: 

 

sage: latex(ceil(x)) # indirect doctest 

\left \lceil x \right \rceil 

""" 

return r"\left \lceil %s \right \rceil"%latex(x) 

 

#FIXME: this should be moved to _eval_ 

def __call__(self, x, **kwds): 

""" 

Allows an object of this class to behave like a function. If 

``ceil`` is an instance of this class, we can do ``ceil(n)`` to get 

the ceiling of ``n``. 

 

TESTS:: 

 

sage: ceil(SR(10^50 + 10^(-50))) 

100000000000000000000000000000000000000000000000001 

sage: ceil(SR(10^50 - 10^(-50))) 

100000000000000000000000000000000000000000000000000 

sage: ceil(int(10^50)) 

100000000000000000000000000000000000000000000000000 

sage: ceil((1725033*pi - 5419351)/(25510582*pi - 80143857)) 

-2 

""" 

return _eval_floor_ceil(self, x, "ceil", **kwds) 

 

def _eval_(self, x): 

""" 

EXAMPLES:: 

 

sage: ceil(x).subs(x==7.5) 

8 

sage: ceil(x) 

ceil(x) 

""" 

try: 

return x.ceil() 

except AttributeError: 

if isinstance(x, integer_types): 

return Integer(x) 

elif isinstance(x, (float, complex)): 

return Integer(math.ceil(x)) 

return None 

 

ceil = Function_ceil() 

 

 

class Function_floor(BuiltinFunction): 

def __init__(self): 

r""" 

The floor function. 

 

The floor of `x` is computed in the following manner. 

 

 

#. The ``x.floor()`` method is called and returned if 

it is there. If it is not, then Sage checks if `x` is one 

of Python's native numeric data types. If so, then it calls and 

returns ``Integer(math.floor(x))``. 

 

#. Sage tries to convert `x` into a 

``RealIntervalField`` with 53 bits of precision. Next, 

the floors of the endpoints are computed. If they are the same, 

then that value is returned. Otherwise, the precision of the 

``RealIntervalField`` is increased until they do match 

up or it reaches ``bits`` of precision. 

 

#. If none of the above work, Sage returns a 

symbolic ``Expression`` object. 

 

 

EXAMPLES:: 

 

sage: floor(5.4) 

5 

sage: type(floor(5.4)) 

<type 'sage.rings.integer.Integer'> 

sage: var('x') 

x 

sage: a = floor(5.4 + x); a 

floor(x + 5.40000000000000) 

sage: a.simplify() 

floor(x + 0.4000000000000004) + 5 

sage: a(x=2) 

7 

 

:: 

 

sage: floor(cos(8) / cos(2)) 

0 

sage: floor(log(4) / log(2)) 

2 

sage: a = floor(5.4 + x); a 

floor(x + 5.40000000000000) 

sage: a.subs(x==2) 

7 

sage: floor(log(2^(3/2)) / log(2) + 1/2) 

2 

sage: floor(log(2^(-3/2)) / log(2) + 1/2) 

-1 

 

:: 

 

sage: floor(factorial(50)/exp(1)) 

11188719610782480504630258070757734324011354208865721592720336800 

sage: floor(SR(10^50 + 10^(-50))) 

100000000000000000000000000000000000000000000000000 

sage: floor(SR(10^50 - 10^(-50))) 

99999999999999999999999999999999999999999999999999 

sage: floor(int(10^50)) 

100000000000000000000000000000000000000000000000000 

 

Small numbers which are extremely close to an integer are hard to 

deal with:: 

 

sage: floor((33^100 + 1)^(1/100)) 

Traceback (most recent call last): 

... 

ValueError: cannot compute floor(...) using 256 bits of precision 

 

This can be fixed by giving a sufficiently large ``bits`` argument:: 

 

sage: floor((33^100 + 1)^(1/100), bits=500) 

Traceback (most recent call last): 

... 

ValueError: cannot compute floor(...) using 512 bits of precision 

sage: floor((33^100 + 1)^(1/100), bits=1000) 

33 

 

:: 

 

sage: import numpy 

sage: a = numpy.linspace(0,2,6) 

sage: floor(a) 

array([ 0., 0., 0., 1., 1., 2.]) 

sage: floor(x)._sympy_() 

floor(x) 

 

Test pickling:: 

 

sage: loads(dumps(floor)) 

floor 

""" 

BuiltinFunction.__init__(self, "floor", 

conversions=dict(sympy='floor', giac='floor')) 

 

def _print_latex_(self, x): 

r""" 

EXAMPLES:: 

 

sage: latex(floor(x)) 

\left \lfloor x \right \rfloor 

""" 

return r"\left \lfloor %s \right \rfloor"%latex(x) 

 

#FIXME: this should be moved to _eval_ 

def __call__(self, x, **kwds): 

""" 

Allows an object of this class to behave like a function. If 

``floor`` is an instance of this class, we can do ``floor(n)`` to 

obtain the floor of ``n``. 

 

TESTS:: 

 

sage: floor(SR(10^50 + 10^(-50))) 

100000000000000000000000000000000000000000000000000 

sage: floor(SR(10^50 - 10^(-50))) 

99999999999999999999999999999999999999999999999999 

sage: floor(int(10^50)) 

100000000000000000000000000000000000000000000000000 

sage: floor((1725033*pi - 5419351)/(25510582*pi - 80143857)) 

-3 

""" 

return _eval_floor_ceil(self, x, "floor", **kwds) 

 

def _eval_(self, x): 

""" 

EXAMPLES:: 

 

sage: floor(x).subs(x==7.5) 

7 

sage: floor(x) 

floor(x) 

""" 

try: 

return x.floor() 

except AttributeError: 

if isinstance(x, integer_types): 

return Integer(x) 

elif isinstance(x, (float, complex)): 

return Integer(math.floor(x)) 

return None 

 

floor = Function_floor() 

 

class Function_Order(GinacFunction): 

def __init__(self): 

r""" 

The order function. 

 

This function gives the order of magnitude of some expression, 

similar to `O`-terms. 

 

.. SEEALSO:: 

 

:meth:`~sage.symbolic.expression.Expression.Order`, 

:mod:`~sage.rings.big_oh` 

 

EXAMPLES:: 

 

sage: x = SR('x') 

sage: x.Order() 

Order(x) 

sage: (x^2 + x).Order() 

Order(x^2 + x) 

sage: x.Order()._sympy_() 

O(x) 

 

TESTS: 

 

Check that :trac:`19425` is resolved:: 

 

sage: x.Order().operator() 

Order 

""" 

GinacFunction.__init__(self, "Order", 

conversions=dict(sympy='O'), 

latex_name=r"\mathcal{O}") 

 

Order = Function_Order() 

 

class Function_frac(BuiltinFunction): 

def __init__(self): 

r""" 

The fractional part function `\{x\}`. 

 

``frac(x)`` is defined as `\{x\} = x - \lfloor x\rfloor`. 

 

EXAMPLES:: 

 

sage: frac(5.4) 

0.400000000000000 

sage: type(frac(5.4)) 

<type 'sage.rings.real_mpfr.RealNumber'> 

sage: frac(456/123) 

29/41 

sage: var('x') 

x 

sage: a = frac(5.4 + x); a 

frac(x + 5.40000000000000) 

sage: frac(cos(8)/cos(2)) 

cos(8)/cos(2) 

sage: latex(frac(x)) 

\operatorname{frac}\left(x\right) 

sage: frac(x)._sympy_() 

frac(x) 

 

Test pickling:: 

 

sage: loads(dumps(floor)) 

floor 

""" 

BuiltinFunction.__init__(self, "frac", 

conversions=dict(sympy='frac'), 

latex_name=r"\operatorname{frac}") 

 

def _evalf_(self, x, **kwds): 

""" 

EXAMPLES:: 

 

sage: frac(pi).n() 

0.141592653589793 

sage: frac(pi).n(200) 

0.14159265358979323846264338327950288419716939937510582097494 

""" 

return x - floor(x) 

 

def _eval_(self, x): 

""" 

EXAMPLES:: 

 

sage: frac(x).subs(x==7.5) 

0.500000000000000 

sage: frac(x) 

frac(x) 

""" 

try: 

return x - x.floor() 

except AttributeError: 

if isinstance(x, integer_types): 

return Integer(0) 

elif isinstance(x, (float, complex)): 

return x - Integer(math.floor(x)) 

elif isinstance(x, Expression): 

ret = floor(x) 

if not hasattr(ret, "operator") or not ret.operator() == floor: 

return x - ret 

return None 

 

frac = Function_frac() 

 

def _do_sqrt(x, prec=None, extend=True, all=False): 

r""" 

Used internally to compute the square root of x. 

 

INPUT: 

 

- ``x`` - a number 

 

- ``prec`` - None (default) or a positive integer 

(bits of precision) If not None, then compute the square root 

numerically to prec bits of precision. 

 

- ``extend`` - bool (default: True); this is a place 

holder, and is always ignored since in the symbolic ring everything 

has a square root. 

 

- ``extend`` - bool (default: True); whether to extend 

the base ring to find roots. The extend parameter is ignored if 

prec is a positive integer. 

 

- ``all`` - bool (default: False); whether to return 

a list of all the square roots of x. 

 

 

EXAMPLES:: 

 

sage: from sage.functions.other import _do_sqrt 

sage: _do_sqrt(3) 

sqrt(3) 

sage: _do_sqrt(3,prec=10) 

1.7 

sage: _do_sqrt(3,prec=100) 

1.7320508075688772935274463415 

sage: _do_sqrt(3,all=True) 

[sqrt(3), -sqrt(3)] 

 

Note that the extend parameter is ignored in the symbolic ring:: 

 

sage: _do_sqrt(3,extend=False) 

sqrt(3) 

""" 

if prec: 

if x >= 0: 

return RealField(prec)(x).sqrt(all=all) 

else: 

return ComplexField(prec)(x).sqrt(all=all) 

if x == -1: 

z = I 

else: 

z = SR(x) ** one_half 

 

if all: 

if z: 

return [z, -z] 

else: 

return [z] 

return z 

 

def sqrt(x, *args, **kwds): 

r""" 

INPUT: 

 

- ``x`` - a number 

 

- ``prec`` - integer (default: None): if None, returns 

an exact square root; otherwise returns a numerical square root if 

necessary, to the given bits of precision. 

 

- ``extend`` - bool (default: True); this is a place 

holder, and is always ignored or passed to the sqrt function for x, 

since in the symbolic ring everything has a square root. 

 

- ``all`` - bool (default: False); if True, return all 

square roots of self, instead of just one. 

 

EXAMPLES:: 

 

sage: sqrt(-1) 

I 

sage: sqrt(2) 

sqrt(2) 

sage: sqrt(2)^2 

2 

sage: sqrt(4) 

2 

sage: sqrt(4,all=True) 

[2, -2] 

sage: sqrt(x^2) 

sqrt(x^2) 

 

For a non-symbolic square root, there are a few options. 

The best is to numerically approximate afterward:: 

 

sage: sqrt(2).n() 

1.41421356237310 

sage: sqrt(2).n(prec=100) 

1.4142135623730950488016887242 

 

Or one can input a numerical type. 

 

sage: sqrt(2.) 

1.41421356237310 

sage: sqrt(2.000000000000000000000000) 

1.41421356237309504880169 

sage: sqrt(4.0) 

2.00000000000000 

 

To prevent automatic evaluation, one can use the ``hold`` parameter 

after coercing to the symbolic ring:: 

 

sage: sqrt(SR(4),hold=True) 

sqrt(4) 

sage: sqrt(4,hold=True) 

Traceback (most recent call last): 

... 

TypeError: _do_sqrt() got an unexpected keyword argument 'hold' 

 

This illustrates that the bug reported in :trac:`6171` has been fixed:: 

 

sage: a = 1.1 

sage: a.sqrt(prec=100) # this is supposed to fail 

Traceback (most recent call last): 

... 

TypeError: sqrt() got an unexpected keyword argument 'prec' 

sage: sqrt(a, prec=100) 

1.0488088481701515469914535137 

sage: sqrt(4.00, prec=250) 

2.0000000000000000000000000000000000000000000000000000000000000000000000000 

 

One can use numpy input as well:: 

 

sage: import numpy 

sage: a = numpy.arange(2,5) 

sage: sqrt(a) 

array([ 1.41421356, 1.73205081, 2. ]) 

""" 

if isinstance(x, float): 

return math.sqrt(x) 

elif type(x).__module__ == 'numpy': 

from numpy import sqrt 

return sqrt(x) 

try: 

return x.sqrt(*args, **kwds) 

# The following includes TypeError to catch cases where sqrt 

# is called with a "prec" keyword, for example, but the sqrt 

# method for x doesn't accept such a keyword. 

except (AttributeError, TypeError): 

pass 

return _do_sqrt(x, *args, **kwds) 

 

# register sqrt in pynac symbol_table for conversion back from other systems 

register_symbol(sqrt, dict(mathematica='Sqrt')) 

symbol_table['functions']['sqrt'] = sqrt 

 

Function_sqrt = type('deprecated_sqrt', (), 

{'__call__': staticmethod(sqrt), 

'__setstate__': lambda x, y: None}) 

 

class Function_arg(BuiltinFunction): 

def __init__(self): 

r""" 

The argument function for complex numbers. 

 

EXAMPLES:: 

 

sage: arg(3+i) 

arctan(1/3) 

sage: arg(-1+i) 

3/4*pi 

sage: arg(2+2*i) 

1/4*pi 

sage: arg(2+x) 

arg(x + 2) 

sage: arg(2.0+i+x) 

arg(x + 2.00000000000000 + 1.00000000000000*I) 

sage: arg(-3) 

pi 

sage: arg(3) 

0 

sage: arg(0) 

0 

 

sage: latex(arg(x)) 

{\rm arg}\left(x\right) 

sage: maxima(arg(x)) 

atan2(0,_SAGE_VAR_x) 

sage: maxima(arg(2+i)) 

atan(1/2) 

sage: maxima(arg(sqrt(2)+i)) 

atan(1/sqrt(2)) 

sage: arg(x)._sympy_() 

arg(x) 

 

sage: arg(2+i) 

arctan(1/2) 

sage: arg(sqrt(2)+i) 

arg(sqrt(2) + I) 

sage: arg(sqrt(2)+i).simplify() 

arctan(1/2*sqrt(2)) 

 

TESTS:: 

 

sage: arg(0.0) 

0.000000000000000 

sage: arg(3.0) 

0.000000000000000 

sage: arg(-2.5) 

3.14159265358979 

sage: arg(2.0+3*i) 

0.982793723247329 

""" 

BuiltinFunction.__init__(self, "arg", 

conversions=dict(maxima='carg', 

mathematica='Arg', 

sympy='arg', 

giac='arg')) 

 

def _eval_(self, x): 

""" 

EXAMPLES:: 

 

sage: arg(3+i) 

arctan(1/3) 

sage: arg(-1+i) 

3/4*pi 

sage: arg(2+2*i) 

1/4*pi 

sage: arg(2+x) 

arg(x + 2) 

sage: arg(2.0+i+x) 

arg(x + 2.00000000000000 + 1.00000000000000*I) 

sage: arg(-3) 

pi 

sage: arg(3) 

0 

sage: arg(0) 

0 

sage: arg(sqrt(2)+i) 

arg(sqrt(2) + I) 

 

""" 

if isinstance(x,Expression): 

if x.is_trivial_zero(): 

return x 

else: 

if not x: 

return x 

else: 

return arctan2(imag_part(x),real_part(x)) 

 

def _evalf_(self, x, parent=None, algorithm=None): 

""" 

EXAMPLES:: 

 

sage: arg(0.0) 

0.000000000000000 

sage: arg(3.0) 

0.000000000000000 

sage: arg(3.00000000000000000000000000) 

0.00000000000000000000000000 

sage: arg(3.00000000000000000000000000).prec() 

90 

sage: arg(ComplexIntervalField(90)(3)).prec() 

90 

sage: arg(ComplexIntervalField(90)(3)).parent() 

Real Interval Field with 90 bits of precision 

sage: arg(3.0r) 

0.0 

sage: arg(RDF(3)) 

0.0 

sage: arg(RDF(3)).parent() 

Real Double Field 

sage: arg(-2.5) 

3.14159265358979 

sage: arg(2.0+3*i) 

0.982793723247329 

 

TESTS: 

 

Make sure that the ``_evalf_`` method works when it receives a 

keyword argument ``parent`` :trac:`12289`:: 

 

sage: arg(5+I, hold=True).n() 

0.197395559849881 

""" 

try: 

return x.arg() 

except AttributeError: 

pass 

# try to find a parent that support .arg() 

if parent is None: 

parent = s_parent(x) 

try: 

parent = parent.complex_field() 

except AttributeError: 

try: 

parent = ComplexField(x.prec()) 

except AttributeError: 

parent = ComplexField() 

 

return parent(x).arg() 

 

arg=Function_arg() 

 

 

############################ 

# Real and Imaginary Parts # 

############################ 

class Function_real_part(GinacFunction): 

def __init__(self): 

r""" 

Returns the real part of the (possibly complex) input. 

 

It is possible to prevent automatic evaluation using the 

``hold`` parameter:: 

 

sage: real_part(I,hold=True) 

real_part(I) 

 

To then evaluate again, we currently must use Maxima via 

:meth:`sage.symbolic.expression.Expression.simplify`:: 

 

sage: real_part(I,hold=True).simplify() 

0 

 

EXAMPLES:: 

 

sage: z = 1+2*I 

sage: real(z) 

1 

sage: real(5/3) 

5/3 

sage: a = 2.5 

sage: real(a) 

2.50000000000000 

sage: type(real(a)) 

<type 'sage.rings.real_mpfr.RealLiteral'> 

sage: real(1.0r) 

1.0 

sage: real(complex(3, 4)) 

3.0 

 

Sage can recognize some expressions as real and accordingly 

return the identical argument:: 

 

sage: SR.var('x', domain='integer').real_part() 

x 

sage: SR.var('x', domain='integer').imag_part() 

0 

sage: real_part(sin(x)+x) 

x + sin(x) 

sage: real_part(x*exp(x)) 

x*e^x 

sage: imag_part(sin(x)+x) 

0 

sage: real_part(real_part(x)) 

x 

sage: forget() 

 

TESTS:: 

 

sage: loads(dumps(real_part)) 

real_part 

sage: real_part(x)._sympy_() 

re(x) 

 

Check if :trac:`6401` is fixed:: 

 

sage: latex(x.real()) 

\Re \left( x \right) 

 

sage: f(x) = function('f')(x) 

sage: latex( f(x).real()) 

\Re \left( f\left(x\right) \right) 

 

Check that some real part expansions evaluate correctly 

(:trac:`21614`):: 

 

sage: real(sqrt(sin(x))).subs(x==0) 

0 

""" 

GinacFunction.__init__(self, "real_part", 

conversions=dict(maxima='realpart', 

sympy='re', 

giac='re'), 

alt_name="real") 

 

def __call__(self, x, **kwargs): 

r""" 

TESTS:: 

 

sage: type(real(complex(3, 4))) 

<... 'float'> 

""" 

if isinstance(x, complex): 

return x.real 

else: 

return GinacFunction.__call__(self, x, **kwargs) 

 

real = real_part = Function_real_part() 

 

class Function_imag_part(GinacFunction): 

def __init__(self): 

r""" 

Returns the imaginary part of the (possibly complex) input. 

 

It is possible to prevent automatic evaluation using the 

``hold`` parameter:: 

 

sage: imag_part(I,hold=True) 

imag_part(I) 

 

To then evaluate again, we currently must use Maxima via 

:meth:`sage.symbolic.expression.Expression.simplify`:: 

 

sage: imag_part(I,hold=True).simplify() 

1 

 

TESTS:: 

 

sage: z = 1+2*I 

sage: imaginary(z) 

2 

sage: imag(z) 

2 

sage: imag(complex(3, 4)) 

4.0 

sage: loads(dumps(imag_part)) 

imag_part 

sage: imag_part(x)._sympy_() 

im(x) 

 

Check if :trac:`6401` is fixed:: 

 

sage: latex(x.imag()) 

\Im \left( x \right) 

 

sage: f(x) = function('f')(x) 

sage: latex( f(x).imag()) 

\Im \left( f\left(x\right) \right) 

""" 

GinacFunction.__init__(self, "imag_part", 

conversions=dict(maxima='imagpart', 

sympy='im', 

giac='im'), 

alt_name="imag") 

 

def __call__(self, x, **kwargs): 

r""" 

TESTS:: 

 

sage: type(imag(complex(3, 4))) 

<... 'float'> 

""" 

if isinstance(x, complex): 

return x.imag 

else: 

return GinacFunction.__call__(self, x, **kwargs) 

 

imag = imag_part = imaginary = Function_imag_part() 

 

 

############################ 

# Complex Conjugate # 

############################ 

class Function_conjugate(GinacFunction): 

def __init__(self): 

r""" 

Returns the complex conjugate of the input. 

 

It is possible to prevent automatic evaluation using the 

``hold`` parameter:: 

 

sage: conjugate(I,hold=True) 

conjugate(I) 

 

To then evaluate again, we currently must use Maxima via 

:meth:`sage.symbolic.expression.Expression.simplify`:: 

 

sage: conjugate(I,hold=True).simplify() 

-I 

 

TESTS:: 

 

sage: x,y = var('x,y') 

sage: x.conjugate() 

conjugate(x) 

sage: _._sympy_() 

conjugate(x) 

sage: latex(conjugate(x)) 

\overline{x} 

sage: f = function('f') 

sage: latex(f(x).conjugate()) 

\overline{f\left(x\right)} 

sage: f = function('psi')(x,y) 

sage: latex(f.conjugate()) 

\overline{\psi\left(x, y\right)} 

sage: x.conjugate().conjugate() 

x 

sage: x.conjugate().operator() 

conjugate 

sage: x.conjugate().operator() == conjugate 

True 

 

Check if :trac:`8755` is fixed:: 

 

sage: conjugate(sqrt(-3)) 

conjugate(sqrt(-3)) 

sage: conjugate(sqrt(3)) 

sqrt(3) 

sage: conjugate(sqrt(x)) 

conjugate(sqrt(x)) 

sage: conjugate(x^2) 

conjugate(x)^2 

sage: var('y',domain='positive') 

y 

sage: conjugate(sqrt(y)) 

sqrt(y) 

 

Check if :trac:`10964` is fixed:: 

 

sage: z= I*sqrt(-3); z 

I*sqrt(-3) 

sage: conjugate(z) 

-I*conjugate(sqrt(-3)) 

sage: var('a') 

a 

sage: conjugate(a*sqrt(-2)*sqrt(-3)) 

conjugate(sqrt(-2))*conjugate(sqrt(-3))*conjugate(a) 

 

Check that sums are handled correctly:: 

 

sage: y = var('y', domain='real') 

sage: conjugate(y + I) 

y - I 

 

Test pickling:: 

 

sage: loads(dumps(conjugate)) 

conjugate 

""" 

GinacFunction.__init__(self, "conjugate", 

conversions=dict(sympy='conjugate', 

giac='conj')) 

 

conjugate = Function_conjugate() 

 

class Function_factorial(GinacFunction): 

def __init__(self): 

r""" 

Returns the factorial of `n`. 

 

INPUT: 

 

- ``n`` - any complex argument (except negative 

integers) or any symbolic expression 

 

 

OUTPUT: an integer or symbolic expression 

 

EXAMPLES:: 

 

sage: x = var('x') 

sage: factorial(0) 

1 

sage: factorial(4) 

24 

sage: factorial(10) 

3628800 

sage: factorial(6) == 6*5*4*3*2 

True 

sage: f = factorial(x + factorial(x)); f 

factorial(x + factorial(x)) 

sage: f(x=3) 

362880 

sage: factorial(x)^2 

factorial(x)^2 

 

To prevent automatic evaluation use the ``hold`` argument:: 

 

sage: factorial(5,hold=True) 

factorial(5) 

 

To then evaluate again, we currently must use Maxima via 

:meth:`sage.symbolic.expression.Expression.simplify`:: 

 

sage: factorial(5,hold=True).simplify() 

120 

 

We can also give input other than nonnegative integers. For 

other nonnegative numbers, the :func:`sage.functions.gamma.gamma` 

function is used:: 

 

sage: factorial(1/2) 

1/2*sqrt(pi) 

sage: factorial(3/4) 

gamma(7/4) 

sage: factorial(2.3) 

2.68343738195577 

 

But negative input always fails:: 

 

sage: factorial(-32) 

Traceback (most recent call last): 

... 

ValueError: factorial -- self = (-32) must be nonnegative 

 

TESTS: 

 

We verify that we can convert this function to Maxima and 

bring it back into Sage.:: 

 

sage: z = var('z') 

sage: factorial._maxima_init_() 

'factorial' 

sage: maxima(factorial(z)) 

factorial(_SAGE_VAR_z) 

sage: _.sage() 

factorial(z) 

sage: _._sympy_() 

factorial(z) 

sage: k = var('k') 

sage: factorial(k) 

factorial(k) 

 

sage: factorial(3.14) 

7.173269190187... 

 

Test latex typesetting:: 

 

sage: latex(factorial(x)) 

x! 

sage: latex(factorial(2*x)) 

\left(2 \, x\right)! 

sage: latex(factorial(sin(x))) 

\sin\left(x\right)! 

sage: latex(factorial(sqrt(x+1))) 

\left(\sqrt{x + 1}\right)! 

sage: latex(factorial(sqrt(x))) 

\sqrt{x}! 

sage: latex(factorial(x^(2/3))) 

\left(x^{\frac{2}{3}}\right)! 

 

sage: latex(factorial) 

{\rm factorial} 

 

Check that :trac:`11539` is fixed:: 

 

sage: (factorial(x) == 0).simplify() 

factorial(x) == 0 

sage: maxima(factorial(x) == 0).sage() 

factorial(x) == 0 

sage: y = var('y') 

sage: (factorial(x) == y).solve(x) 

[factorial(x) == y] 

 

Check that :trac:`16166` is fixed:: 

 

sage: RBF=RealBallField(53) 

sage: factorial(RBF(4.2)) 

[32.5780960503313 +/- 6.72e-14] 

 

Test pickling:: 

 

sage: loads(dumps(factorial)) 

factorial 

""" 

GinacFunction.__init__(self, "factorial", latex_name='{\\rm factorial}', 

conversions=dict(maxima='factorial', 

mathematica='Factorial', 

sympy='factorial', 

fricas='factorial', 

giac='factorial')) 

 

def _eval_(self, x): 

""" 

Evaluate the factorial function. 

 

Note that this method overrides the eval method defined in GiNaC 

which calls numeric evaluation on all numeric input. We preserve 

exact results if the input is a rational number. 

 

EXAMPLES:: 

 

sage: k = var('k') 

sage: k.factorial() 

factorial(k) 

sage: SR(1/2).factorial() 

1/2*sqrt(pi) 

sage: SR(3/4).factorial() 

gamma(7/4) 

sage: SR(5).factorial() 

120 

sage: SR(3245908723049857203948572398475r).factorial() 

factorial(3245908723049857203948572398475) 

sage: SR(3245908723049857203948572398475).factorial() 

factorial(3245908723049857203948572398475) 

""" 

from sage.functions.gamma import gamma 

if isinstance(x, Rational): 

return gamma(x+1) 

elif isinstance(x, (Integer, int)) or self._is_numerical(x): 

return py_factorial_py(x) 

 

return None 

 

factorial = Function_factorial() 

 

class Function_binomial(GinacFunction): 

def __init__(self): 

r""" 

Return the binomial coefficient 

 

.. MATH:: 

 

\binom{x}{m} = x (x-1) \cdots (x-m+1) / m! 

 

 

which is defined for `m \in \ZZ` and any 

`x`. We extend this definition to include cases when 

`x-m` is an integer but `m` is not by 

 

.. MATH:: 

 

\binom{x}{m}= \binom{x}{x-m} 

 

If `m < 0`, return `0`. 

 

INPUT: 

 

- ``x``, ``m`` - numbers or symbolic expressions. Either ``m`` 

or ``x-m`` must be an integer, else the output is symbolic. 

 

OUTPUT: number or symbolic expression (if input is symbolic) 

 

EXAMPLES:: 

 

sage: binomial(5,2) 

10 

sage: binomial(2,0) 

1 

sage: binomial(1/2, 0) 

1 

sage: binomial(3,-1) 

0 

sage: binomial(20,10) 

184756 

sage: binomial(-2, 5) 

-6 

sage: binomial(RealField()('2.5'), 2) 

1.87500000000000 

sage: n=var('n'); binomial(n,2) 

1/2*(n - 1)*n 

sage: n=var('n'); binomial(n,n) 

1 

sage: n=var('n'); binomial(n,n-1) 

n 

sage: binomial(2^100, 2^100) 

1 

 

:: 

 

sage: k, i = var('k,i') 

sage: binomial(k,i) 

binomial(k, i) 

 

We can use a ``hold`` parameter to prevent automatic evaluation:: 

 

sage: SR(5).binomial(3, hold=True) 

binomial(5, 3) 

sage: SR(5).binomial(3, hold=True).simplify() 

10 

 

TESTS: 

 

We verify that we can convert this function to Maxima and 

bring it back into Sage. 

 

:: 

 

sage: n,k = var('n,k') 

sage: maxima(binomial(n,k)) 

binomial(_SAGE_VAR_n,_SAGE_VAR_k) 

sage: _.sage() 

binomial(n, k) 

sage: _._sympy_() 

binomial(n, k) 

sage: binomial._maxima_init_() 

'binomial' 

 

For polynomials:: 

 

sage: y = polygen(QQ, 'y') 

sage: binomial(y, 2).parent() 

Univariate Polynomial Ring in y over Rational Field 

 

:trac:`16726`:: 

 

sage: binomial(CIF(1), 2) 

0 

sage: binomial(CIF(3), 2) 

3 

 

Test pickling:: 

 

sage: loads(dumps(binomial(n,k))) 

binomial(n, k) 

""" 

GinacFunction.__init__(self, "binomial", nargs=2, preserved_arg=1, 

conversions=dict(maxima='binomial', 

mathematica='Binomial', 

sympy='binomial', 

fricas='binomial', 

giac='comb')) 

 

def _binomial_sym(self, n, k): 

""" 

Expand the binomial formula symbolically when the second argument 

is an integer. 

 

EXAMPLES:: 

 

sage: binomial._binomial_sym(x, 3) 

1/6*(x - 1)*(x - 2)*x 

sage: binomial._binomial_sym(x, x) 

Traceback (most recent call last): 

... 

ValueError: second argument must be an integer 

sage: binomial._binomial_sym(x, SR(3)) 

1/6*(x - 1)*(x - 2)*x 

 

sage: binomial._binomial_sym(x, 0r) 

1 

sage: binomial._binomial_sym(x, -1) 

0 

 

sage: y = polygen(QQ, 'y') 

sage: binomial._binomial_sym(y, 2).parent() 

Univariate Polynomial Ring in y over Rational Field 

""" 

if isinstance(k, Expression): 

if k.is_integer(): 

k = k.pyobject() 

else: 

raise ValueError("second argument must be an integer") 

 

if k < 0: 

return s_parent(k)(0) 

if k == 0: 

return s_parent(k)(1) 

if k == 1: 

return n 

 

from sage.misc.all import prod 

return prod(n - i for i in range(k)) / factorial(k) 

 

def _eval_(self, n, k): 

""" 

EXAMPLES:: 

 

sage: binomial._eval_(5, 3) 

10 

sage: type(binomial._eval_(5, 3)) 

<type 'sage.rings.integer.Integer'> 

sage: type(binomial._eval_(5., 3)) 

<type 'sage.rings.real_mpfr.RealNumber'> 

sage: binomial._eval_(x, 3) 

1/6*(x - 1)*(x - 2)*x 

sage: binomial._eval_(x, x-2) 

1/2*(x - 1)*x 

sage: n = var('n') 

sage: binomial._eval_(x, n) is None 

True 

 

TESTS:: 

 

sage: y = polygen(QQ, 'y') 

sage: binomial._eval_(y, 2).parent() 

Univariate Polynomial Ring in y over Rational Field 

""" 

if not isinstance(k, Expression): 

if not isinstance(n, Expression): 

n, k = coercion_model.canonical_coercion(n, k) 

return self._evalf_(n, k) 

if k in ZZ: 

return self._binomial_sym(n, k) 

if (n - k) in ZZ: 

return self._binomial_sym(n, n - k) 

 

return None 

 

def _evalf_(self, n, k, parent=None, algorithm=None): 

""" 

EXAMPLES:: 

 

sage: binomial._evalf_(5.r, 3) 

10.0 

sage: type(binomial._evalf_(5.r, 3)) 

<... 'float'> 

sage: binomial._evalf_(1/2,1/1) 

1/2 

sage: binomial._evalf_(10^20+1/1,10^20) 

100000000000000000001 

sage: binomial._evalf_(SR(10**7),10**7) 

1 

sage: binomial._evalf_(3/2,SR(1/1)) 

3/2 

""" 

return arith_binomial(n, k) 

 

binomial = Function_binomial() 

 

 

class Function_sum(BuiltinFunction): 

""" 

Placeholder symbolic sum function that is only accessible internally. 

 

EXAMPLES:: 

 

sage: from sage.functions.other import symbolic_sum as ssum 

sage: r = ssum(x, x, 1, 10); r 

sum(x, x, 1, 10) 

sage: r.unhold() 

55 

""" 

def __init__(self): 

""" 

EXAMPLES:: 

 

sage: from sage.functions.other import symbolic_sum as ssum 

sage: maxima(ssum(x, x, 1, 10)) 

55 

""" 

BuiltinFunction.__init__(self, "sum", nargs=4, 

conversions=dict(maxima='sum')) 

 

def _print_latex_(self, x, var, a, b): 

r""" 

EXAMPLES:: 

 

sage: from sage.functions.other import symbolic_sum as ssum 

sage: latex(ssum(x^2, x, 1, 10)) 

{\sum_{x=1}^{10} x^{2}} 

""" 

return r"{{\sum_{{{}={}}}^{{{}}} {}}}".format(latex(var), latex(a), 

latex(b), latex(x)) 

 

symbolic_sum = Function_sum() 

 

 

class Function_prod(BuiltinFunction): 

""" 

Placeholder symbolic product function that is only accessible internally. 

 

EXAMPLES:: 

 

sage: from sage.functions.other import symbolic_product as sprod 

sage: r = sprod(x, x, 1, 10); r 

product(x, x, 1, 10) 

sage: r.unhold() 

3628800 

""" 

def __init__(self): 

""" 

EXAMPLES:: 

 

sage: from sage.functions.other import symbolic_product as sprod 

sage: _ = var('m n', domain='integer') 

sage: r = maxima(sprod(sin(m), m, 1, n)).sage(); r 

product(sin(m), m, 1, n) 

sage: isinstance(r.operator(), sage.functions.other.Function_prod) 

True 

sage: r = sympy(sprod(sin(m), m, 1, n)).sage(); r # known bug 

product(sin(m), m, 1, n) 

sage: isinstance(r.operator(), 

....: sage.functions.other.Function_prod) # known bug 

True 

sage: giac(sprod(m, m, 1, n)) 

n! 

""" 

BuiltinFunction.__init__(self, "product", nargs=4, 

conversions=dict(maxima='product', 

sympy='Product', giac='product')) 

 

def _print_latex_(self, x, var, a, b): 

r""" 

EXAMPLES:: 

 

sage: from sage.functions.other import symbolic_product as sprod 

sage: latex(sprod(x^2, x, 1, 10)) 

{\prod_{x=1}^{10} x^{2}} 

""" 

return r"{{\prod_{{{}={}}}^{{{}}} {}}}".format(latex(var), latex(a), 

latex(b), latex(x)) 

 

symbolic_product = Function_prod() 

 

 

class Function_limit(BuiltinFunction): 

""" 

Placeholder symbolic limit function that is only accessible internally. 

 

This function is called to create formal wrappers of limits that 

Maxima can't compute:: 

 

sage: a = lim(exp(x^2)*(1-erf(x)), x=infinity); a 

-limit((erf(x) - 1)*e^(x^2), x, +Infinity) 

 

EXAMPLES:: 

 

sage: from sage.functions.other import symbolic_limit as slimit 

sage: slimit(1/x, x, +oo) 

limit(1/x, x, +Infinity) 

sage: var('minus,plus') 

(minus, plus) 

sage: slimit(1/x, x, +oo) 

limit(1/x, x, +Infinity) 

sage: slimit(1/x, x, 0, plus) 

limit(1/x, x, 0, plus) 

sage: slimit(1/x, x, 0, minus) 

limit(1/x, x, 0, minus) 

""" 

def __init__(self): 

""" 

EXAMPLES:: 

 

sage: from sage.functions.other import symbolic_limit as slimit 

sage: maxima(slimit(1/x, x, +oo)) 

0 

""" 

BuiltinFunction.__init__(self, "limit", nargs=0, 

conversions=dict(maxima='limit')) 

 

def _latex_(self): 

r""" 

EXAMPLES:: 

 

sage: from sage.functions.other import symbolic_limit as slimit 

sage: latex(slimit) 

\lim 

""" 

return r'\lim' 

 

def _print_latex_(self, ex, var, to, direction=''): 

r""" 

EXAMPLES:: 

 

sage: from sage.functions.other import symbolic_limit as slimit 

sage: var('x,a') 

(x, a) 

sage: f = function('f') 

sage: latex(slimit(f(x), x, a)) 

\lim_{x \to a}\, f\left(x\right) 

sage: latex(limit(f(x), x=oo)) 

\lim_{x \to +\infty}\, f\left(x\right) 

 

TESTS: 

 

When one-sided limits are converted back from maxima, the direction 

argument becomes a symbolic variable. We check if typesetting these works:: 

 

sage: from sage.functions.other import symbolic_limit as slimit 

sage: var('minus,plus') 

(minus, plus) 

sage: latex(slimit(f(x), x, a, minus)) 

\lim_{x \to a^-}\, f\left(x\right) 

sage: latex(slimit(f(x), x, a, plus)) 

\lim_{x \to a^+}\, f\left(x\right) 

sage: latex(limit(f(x),x=a,dir='+')) 

\lim_{x \to a^+}\, f\left(x\right) 

sage: latex(limit(f(x),x=a,dir='right')) 

\lim_{x \to a^+}\, f\left(x\right) 

sage: latex(limit(f(x),x=a,dir='-')) 

\lim_{x \to a^-}\, f\left(x\right) 

sage: latex(limit(f(x),x=a,dir='left')) 

\lim_{x \to a^-}\, f\left(x\right) 

 

Check if :trac:`13181` is fixed:: 

 

sage: t = var('t') 

sage: latex(limit(exp_integral_e(1/2, I*t - I*x)*sqrt(-t + x),t=x,dir='-')) 

\lim_{t \to x^-}\, \sqrt{-t + x} exp_integral_e\left(\frac{1}{2}, i \, t - i \, x\right) 

sage: latex(limit(exp_integral_e(1/2, I*t - I*x)*sqrt(-t + x),t=x,dir='+')) 

\lim_{t \to x^+}\, \sqrt{-t + x} exp_integral_e\left(\frac{1}{2}, i \, t - i \, x\right) 

sage: latex(limit(exp_integral_e(1/2, I*t - I*x)*sqrt(-t + x),t=x)) 

\lim_{t \to x}\, \sqrt{-t + x} exp_integral_e\left(\frac{1}{2}, i \, t - i \, x\right) 

""" 

if repr(direction) == 'minus': 

dir_str = '^-' 

elif repr(direction) == 'plus': 

dir_str = '^+' 

else: 

dir_str = '' 

return r"\lim_{{{} \to {}{}}}\, {}".format(latex(var), 

latex(to), dir_str, latex(ex)) 

 

symbolic_limit = Function_limit() 

 

 

class Function_cases(GinacFunction): 

""" 

Formal function holding ``(condition, expression)`` pairs. 

 

Numbers are considered conditions with zero being ``False``. 

A true condition marks a default value. The function is not 

evaluated as long as it contains a relation that cannot be 

decided by Pynac. 

 

EXAMPLES:: 

 

sage: ex = cases([(x==0, pi), (True, 0)]); ex 

cases(((x == 0, pi), (1, 0))) 

sage: ex.subs(x==0) 

pi 

sage: ex.subs(x==2) 

0 

sage: ex + 1 

cases(((x == 0, pi), (1, 0))) + 1 

sage: _.subs(x==0) 

pi + 1 

 

The first encountered default is used, as well as the first relation 

that can be trivially decided:: 

 

sage: cases(((True, pi), (True, 0))) 

pi 

 

sage: _ = var('y') 

sage: ex = cases(((x==0, pi), (y==1, 0))); ex 

cases(((x == 0, pi), (y == 1, 0))) 

sage: ex.subs(x==0) 

pi 

sage: ex.subs(x==0, y==1) 

pi 

""" 

def __init__(self): 

""" 

EXAMPLES:: 

 

sage: loads(dumps(cases)) 

cases 

""" 

GinacFunction.__init__(self, "cases") 

 

def __call__(self, l, **kwargs): 

""" 

EXAMPLES:: 

 

sage: ex = cases([(x==0, pi), (True, 0)]); ex 

cases(((x == 0, pi), (1, 0))) 

 

TESTS:: 

 

sage: cases() 

Traceback (most recent call last): 

... 

TypeError: __call__() takes exactly 2 arguments (1 given) 

 

sage: cases(x) 

Traceback (most recent call last): 

... 

RuntimeError: cases argument not a sequence 

""" 

return GinacFunction.__call__(self, 

SR._force_pyobject(l), **kwargs) 

 

def _print_latex_(self, l, **kwargs): 

r""" 

EXAMPLES:: 

 

sage: ex = cases([(x==0, pi), (True, 0)]); ex 

cases(((x == 0, pi), (1, 0))) 

sage: latex(ex) 

\begin{cases}{\pi} & {x = 0}\\{0} & {1}\end{cases} 

""" 

if not isinstance(l, (list, tuple)): 

raise ValueError("cases() argument must be a list") 

str = r"\begin{cases}" 

for pair in l: 

left = None 

if (isinstance(pair, tuple)): 

right,left = pair 

else: 

right = pair 

str += r"{%s} & {%s}\\" % (latex(left), latex(right)) 

print(str[:-2] + r"\end{cases}") 

 

def _sympy_(self, l): 

""" 

Convert this cases expression to its SymPy equivalent. 

 

EXAMPLES:: 

 

sage: ex = cases(((x<0, pi), (x==1, 1), (True, 0))) 

sage: assert ex == ex._sympy_()._sage_() 

""" 

from sage.symbolic.ring import SR 

from sympy import Piecewise as pw 

args = [] 

for tup in l.operands(): 

cond,expr = tup.operands() 

if SR(cond).is_numeric(): 

args.append((SR(expr)._sympy_(), bool(SR(cond)._sympy_()))) 

else: 

args.append((SR(expr)._sympy_(), SR(cond)._sympy_())) 

return pw(*args) 

 

cases = Function_cases() 

 

 

class Function_crootof(BuiltinFunction): 

""" 

Formal function holding ``(polynomial, index)`` pairs. 

 

The expression evaluates to a floating point value that is an 

approximation to a specific complex root of the polynomial. The 

ordering is fixed so you always get the same root. 

 

The functionality is imported from SymPy, see 

http://docs.sympy.org/latest/_modules/sympy/polys/rootoftools.html 

 

EXAMPLES:: 

 

sage: c = complex_root_of(x^6 + x + 1, 1); c 

complex_root_of(x^6 + x + 1, 1) 

sage: c.n() 

-0.790667188814418 + 0.300506920309552*I 

sage: c.n(100) 

-0.79066718881441764449859281847 + 0.30050692030955162512001002521*I 

sage: (c^6 + c + 1).n(100) < 1e-25 

True 

""" 

def __init__(self): 

""" 

EXAMPLES:: 

 

sage: loads(dumps(complex_root_of)) 

complex_root_of 

""" 

BuiltinFunction.__init__(self, "complex_root_of", nargs=2, 

conversions=dict(sympy='CRootOf'), 

evalf_params_first=False) 

 

def _eval_(self, poly, index): 

""" 

TESTS:: 

 

sage: _ = var('y') 

sage: complex_root_of(1, 1) 

Traceback (most recent call last): 

... 

ValueError: polynomial in one variable required 

sage: complex_root_of(x+y, 1) 

Traceback (most recent call last): 

... 

ValueError: polynomial in one variable required 

sage: complex_root_of(sin(x), 1) 

Traceback (most recent call last): 

... 

ValueError: polynomial in one variable required 

""" 

try: 

vars = poly.variables() 

except AttributeError: 

raise ValueError('polynomial in one variable required') 

if len(vars) != 1 or not poly.is_polynomial(vars[0]): 

raise ValueError('polynomial in one variable required') 

 

def _evalf_(self, poly, index, parent=None, algorithm=None): 

""" 

EXAMPLES:: 

 

sage: complex_root_of(x^2-2, 1).n() 

1.41421356237309 

sage: complex_root_of(x^2-2, 3).n() 

Traceback (most recent call last): 

... 

IndexError: root index out of [-2, 1] range, got 3 

 

TESTS: 

 

Check that low precision is handled (:trac:`24378`):: 

 

sage: complex_root_of(x^8-1, 7).n(2) 

0.75 + 0.75*I 

sage: complex_root_of(x^8-1, 7).n(20) 

0.70711 + 0.70711*I 

""" 

from sympy.core.evalf import prec_to_dps 

from sympy.polys import CRootOf, Poly 

try: 

prec = parent.precision() 

except AttributeError: 

prec = 53 

sobj = CRootOf(Poly(poly._sympy_()), int(index)) 

return parent(sobj.n(1 + prec_to_dps(prec))._sage_()) 

 

complex_root_of = Function_crootof()