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

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

2060

2061

2062

2063

2064

2065

2066

2067

2068

2069

2070

2071

2072

2073

2074

2075

2076

2077

2078

2079

2080

2081

2082

2083

2084

2085

2086

2087

2088

2089

2090

2091

2092

2093

2094

2095

2096

2097

2098

2099

2100

2101

2102

2103

2104

2105

2106

2107

2108

2109

2110

2111

2112

2113

2114

2115

2116

2117

2118

2119

2120

2121

2122

2123

2124

2125

2126

2127

2128

2129

2130

2131

2132

2133

2134

2135

2136

2137

2138

2139

2140

2141

2142

2143

2144

2145

2146

2147

2148

2149

2150

2151

2152

2153

2154

2155

2156

2157

2158

2159

2160

2161

2162

2163

2164

2165

2166

2167

2168

2169

2170

2171

2172

2173

2174

2175

2176

2177

2178

2179

2180

2181

2182

2183

2184

2185

2186

2187

2188

2189

2190

2191

2192

2193

2194

2195

2196

2197

2198

2199

2200

2201

2202

2203

2204

2205

2206

2207

2208

2209

2210

2211

2212

2213

2214

2215

2216

2217

2218

2219

2220

2221

2222

2223

2224

2225

2226

2227

2228

2229

2230

2231

2232

2233

2234

2235

2236

2237

2238

2239

2240

2241

2242

2243

2244

2245

2246

2247

2248

2249

2250

2251

2252

2253

2254

2255

2256

2257

2258

2259

2260

2261

2262

2263

2264

2265

2266

2267

2268

2269

2270

2271

2272

2273

2274

2275

2276

2277

2278

2279

2280

2281

2282

2283

2284

2285

2286

2287

2288

2289

2290

2291

2292

2293

2294

2295

2296

2297

2298

2299

2300

2301

2302

2303

2304

2305

2306

2307

2308

2309

2310

2311

2312

2313

2314

2315

2316

2317

2318

2319

2320

2321

2322

2323

2324

2325

2326

2327

2328

2329

2330

2331

2332

2333

2334

2335

2336

2337

2338

2339

2340

2341

2342

2343

2344

2345

2346

2347

2348

2349

2350

2351

2352

2353

2354

2355

2356

2357

2358

2359

r""" 

Symbolic Computation 

 

AUTHORS: 

 

- Bobby Moretti and William Stein (2006-2007) 

 

- Robert Bradshaw (2007-10): minpoly(), numerical algorithm 

 

- Robert Bradshaw (2008-10): minpoly(), algebraic algorithm 

 

- Golam Mortuza Hossain (2009-06-15): _limit_latex() 

 

- Golam Mortuza Hossain (2009-06-22): _laplace_latex(), _inverse_laplace_latex() 

 

- Tom Coates (2010-06-11): fixed :trac:`9217` 

 

EXAMPLES: 

 

The basic units of the calculus package are symbolic expressions which 

are elements of the symbolic expression ring (SR). To create a 

symbolic variable object in Sage, use the :func:`var` function, whose 

argument is the text of that variable. Note that Sage is intelligent 

about LaTeXing variable names. 

 

:: 

 

sage: x1 = var('x1'); x1 

x1 

sage: latex(x1) 

x_{1} 

sage: theta = var('theta'); theta 

theta 

sage: latex(theta) 

\theta 

 

Sage predefines ``x`` to be a global indeterminate. 

Thus the following works:: 

 

sage: x^2 

x^2 

sage: type(x) 

<type 'sage.symbolic.expression.Expression'> 

 

More complicated expressions in Sage can be built up using ordinary 

arithmetic. The following are valid, and follow the rules of Python 

arithmetic: (The '=' operator represents assignment, and not 

equality) 

 

:: 

 

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

(x, y, z) 

sage: f = x + y + z/(2*sin(y*z/55)) 

sage: g = f^f; g 

(x + y + 1/2*z/sin(1/55*y*z))^(x + y + 1/2*z/sin(1/55*y*z)) 

 

Differentiation and integration are available, but behind the 

scenes through Maxima:: 

 

sage: f = sin(x)/cos(2*y) 

sage: f.derivative(y) 

2*sin(x)*sin(2*y)/cos(2*y)^2 

sage: g = f.integral(x); g 

-cos(x)/cos(2*y) 

 

Note that these methods usually require an explicit variable name. If none 

is given, Sage will try to find one for you. 

 

:: 

 

sage: f = sin(x); f.derivative() 

cos(x) 

 

If the expression is a callable symbolic expression (i.e., the 

variable order is specified), then Sage can calculate the matrix 

derivative (i.e., the gradient, Jacobian matrix, etc.) if no variables 

are specified. In the example below, we use the second derivative 

test to determine that there is a saddle point at (0,-1/2). 

 

:: 

 

sage: f(x,y)=x^2*y+y^2+y 

sage: f.diff() # gradient 

(x, y) |--> (2*x*y, x^2 + 2*y + 1) 

sage: solve(list(f.diff()),[x,y]) 

[[x == -I, y == 0], [x == I, y == 0], [x == 0, y == (-1/2)]] 

sage: H=f.diff(2); H # Hessian matrix 

[(x, y) |--> 2*y (x, y) |--> 2*x] 

[(x, y) |--> 2*x (x, y) |--> 2] 

sage: H(x=0,y=-1/2) 

[-1 0] 

[ 0 2] 

sage: H(x=0,y=-1/2).eigenvalues() 

[-1, 2] 

 

Here we calculate the Jacobian for the polar coordinate transformation:: 

 

sage: T(r,theta)=[r*cos(theta),r*sin(theta)] 

sage: T 

(r, theta) |--> (r*cos(theta), r*sin(theta)) 

sage: T.diff() # Jacobian matrix 

[ (r, theta) |--> cos(theta) (r, theta) |--> -r*sin(theta)] 

[ (r, theta) |--> sin(theta) (r, theta) |--> r*cos(theta)] 

sage: diff(T) # Jacobian matrix 

[ (r, theta) |--> cos(theta) (r, theta) |--> -r*sin(theta)] 

[ (r, theta) |--> sin(theta) (r, theta) |--> r*cos(theta)] 

sage: T.diff().det() # Jacobian 

(r, theta) |--> r*cos(theta)^2 + r*sin(theta)^2 

 

When the order of variables is ambiguous, Sage will raise an 

exception when differentiating:: 

 

sage: f = sin(x+y); f.derivative() 

Traceback (most recent call last): 

... 

ValueError: No differentiation variable specified. 

 

Simplifying symbolic sums is also possible, using the 

sum command, which also uses Maxima in the background:: 

 

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

sage: sum(1/k^4, k, 1, oo) 

1/90*pi^4 

sage: sum(binomial(m,k), k, 0, m) 

2^m 

 

Symbolic matrices can be used as well in various ways, 

including exponentiation:: 

 

sage: M = matrix([[x,x^2],[1/x,x]]) 

sage: M^2 

[x^2 + x 2*x^3] 

[ 2 x^2 + x] 

sage: e^M 

[ 1/2*(e^(2*sqrt(x)) + 1)*e^(x - sqrt(x)) 1/2*(x*e^(2*sqrt(x)) - x)*sqrt(x)*e^(x - sqrt(x))] 

[ 1/2*(e^(2*sqrt(x)) - 1)*e^(x - sqrt(x))/x^(3/2) 1/2*(e^(2*sqrt(x)) + 1)*e^(x - sqrt(x))] 

 

And complex exponentiation works now:: 

 

sage: M = i*matrix([[pi]]) 

sage: e^M 

[-1] 

sage: M = i*matrix([[pi,0],[0,2*pi]]) 

sage: e^M 

[-1 0] 

[ 0 1] 

sage: M = matrix([[0,pi],[-pi,0]]) 

sage: e^M 

[-1 0] 

[ 0 -1] 

 

Substitution works similarly. We can substitute with a python 

dict:: 

 

sage: f = sin(x*y - z) 

sage: f({x: var('t'), y: z}) 

sin(t*z - z) 

 

Also we can substitute with keywords:: 

 

sage: f = sin(x*y - z) 

sage: f(x = t, y = z) 

sin(t*z - z) 

 

It was formerly the case that if there was no ambiguity of variable 

names, we didn't have to specify them; that still works for the moment, 

but the behavior is deprecated:: 

 

sage: f = sin(x) 

sage: f(y) 

doctest:...: DeprecationWarning: Substitution using function-call 

syntax and unnamed arguments is deprecated and will be removed 

from a future release of Sage; you can use named arguments instead, 

like EXPR(x=..., y=...) 

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

sin(y) 

sage: f(pi) 

0 

 

However if there is ambiguity, we should explicitly state what 

variables we're substituting for:: 

 

sage: f = sin(2*pi*x/y) 

sage: f(x=4) 

sin(8*pi/y) 

 

We can also make a ``CallableSymbolicExpression``, 

which is a ``SymbolicExpression`` that is a function of 

specified variables in a fixed order. Each 

``SymbolicExpression`` has a 

``function(...)`` method that is used to create a 

``CallableSymbolicExpression``, as illustrated below:: 

 

sage: u = log((2-x)/(y+5)) 

sage: f = u.function(x, y); f 

(x, y) |--> log(-(x - 2)/(y + 5)) 

 

There is an easier way of creating a 

``CallableSymbolicExpression``, which relies on the 

Sage preparser. 

 

:: 

 

sage: f(x,y) = log(x)*cos(y); f 

(x, y) |--> cos(y)*log(x) 

 

Then we have fixed an order of variables and there is no ambiguity 

substituting or evaluating:: 

 

sage: f(x,y) = log((2-x)/(y+5)) 

sage: f(7,t) 

log(-5/(t + 5)) 

 

Some further examples:: 

 

sage: f = 5*sin(x) 

sage: f 

5*sin(x) 

sage: f(x=2) 

5*sin(2) 

sage: f(x=pi) 

0 

sage: float(f(x=pi)) 

0.0 

 

Another example:: 

 

sage: f = integrate(1/sqrt(9+x^2), x); f 

arcsinh(1/3*x) 

sage: f(x=3) 

arcsinh(1) 

sage: f.derivative(x) 

1/3/sqrt(1/9*x^2 + 1) 

 

We compute the length of the parabola from 0 to 2:: 

 

sage: x = var('x') 

sage: y = x^2 

sage: dy = derivative(y,x) 

sage: z = integral(sqrt(1 + dy^2), x, 0, 2) 

sage: z 

sqrt(17) + 1/4*arcsinh(4) 

sage: n(z,200) 

4.6467837624329358733826155674904591885104869874232887508703 

sage: float(z) 

4.646783762432936 

 

We test pickling:: 

 

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

sage: f = -sqrt(pi)*(x^3 + sin(x/cos(y))) 

sage: bool(loads(dumps(f)) == f) 

True 

 

Coercion examples: 

 

We coerce various symbolic expressions into the complex numbers:: 

 

sage: CC(I) 

1.00000000000000*I 

sage: CC(2*I) 

2.00000000000000*I 

sage: ComplexField(200)(2*I) 

2.0000000000000000000000000000000000000000000000000000000000*I 

sage: ComplexField(200)(sin(I)) 

1.1752011936438014568823818505956008151557179813340958702296*I 

sage: f = sin(I) + cos(I/2); f 

cosh(1/2) + I*sinh(1) 

sage: CC(f) 

1.12762596520638 + 1.17520119364380*I 

sage: ComplexField(200)(f) 

1.1276259652063807852262251614026720125478471180986674836290 + 1.1752011936438014568823818505956008151557179813340958702296*I 

sage: ComplexField(100)(f) 

1.1276259652063807852262251614 + 1.1752011936438014568823818506*I 

 

We illustrate construction of an inverse sum where each denominator 

has a new variable name:: 

 

sage: f = sum(1/var('n%s'%i)^i for i in range(10)) 

sage: f 

1/n1 + 1/n2^2 + 1/n3^3 + 1/n4^4 + 1/n5^5 + 1/n6^6 + 1/n7^7 + 1/n8^8 + 1/n9^9 + 1 

 

Note that after calling var, the variables are immediately 

available for use:: 

 

sage: (n1 + n2)^5 

(n1 + n2)^5 

 

We can, of course, substitute:: 

 

sage: f(n9=9,n7=n6) 

1/n1 + 1/n2^2 + 1/n3^3 + 1/n4^4 + 1/n5^5 + 1/n6^6 + 1/n6^7 + 1/n8^8 + 387420490/387420489 

 

TESTS: 

 

Substitution:: 

 

sage: f = x 

sage: f(x=5) 

5 

 

Simplifying expressions involving scientific notation:: 

 

sage: k = var('k') 

sage: a0 = 2e-06; a1 = 12 

sage: c = a1 + a0*k; c 

(2.00000000000000e-6)*k + 12 

sage: sqrt(c) 

sqrt((2.00000000000000e-6)*k + 12) 

sage: sqrt(c^3) 

sqrt(((2.00000000000000e-6)*k + 12)^3) 

 

The symbolic calculus package uses its own copy of Maxima for 

simplification, etc., which is separate from the default 

system-wide version:: 

 

sage: maxima.eval('[x,y]: [1,2]') 

'[1,2]' 

sage: maxima.eval('expand((x+y)^3)') 

'27' 

 

If the copy of maxima used by the symbolic calculus package were 

the same as the default one, then the following would return 27, 

which would be very confusing indeed! 

 

:: 

 

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

sage: expand((x+y)^3) 

x^3 + 3*x^2*y + 3*x*y^2 + y^3 

 

Set x to be 5 in maxima:: 

 

sage: maxima('x: 5') 

5 

sage: maxima('x + x + %pi') 

%pi+10 

 

Simplifications like these are now done using Pynac:: 

 

sage: x + x + pi 

pi + 2*x 

 

But this still uses Maxima:: 

 

sage: (x + x + pi).simplify() 

pi + 2*x 

 

Note that ``x`` is still ``x``, since the 

maxima used by the calculus package is different than the one in 

the interactive interpreter. 

 

Check to see that the problem with the variables method mentioned 

in :trac:`3779` is actually fixed:: 

 

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

sage: diff(f*SR(1),x) 

diff(F(x), x) 

 

Doubly ensure that :trac:`7479` is working:: 

 

sage: f(x)=x 

sage: integrate(f,x,0,1) 

1/2 

 

Check that the problem with Taylor expansions of the gamma function 

(:trac:`9217`) is fixed:: 

 

sage: taylor(gamma(1/3+x),x,0,3) 

-1/432*((72*euler_gamma^3 + 36*euler_gamma^2*(sqrt(3)*pi + 9*log(3)) + ... 

sage: [f[0].n() for f in _.coefficients()] # numerical coefficients to make comparison easier; Maple 12 gives same answer 

[2.6789385347..., -8.3905259853..., 26.662447494..., -80.683148377...] 

 

Ensure that :trac:`8582` is fixed:: 

 

sage: k = var("k") 

sage: sum(1/(1+k^2), k, -oo, oo) 

-1/2*I*psi(I + 1) + 1/2*I*psi(-I + 1) - 1/2*I*psi(I) + 1/2*I*psi(-I) 

 

Ensure that :trac:`8624` is fixed:: 

 

sage: integrate(abs(cos(x)) * sin(x), x, pi/2, pi) 

1/2 

sage: integrate(sqrt(cos(x)^2 + sin(x)^2), x, 0, 2*pi) 

2*pi 

 

Check if maxima has redundant variables defined after initialization, 

see :trac:`9538`:: 

 

sage: maxima = sage.interfaces.maxima.maxima 

sage: maxima('f1') 

f1 

sage: sage.calculus.calculus.maxima('f1') 

f1 

""" 

 

import re 

from sage.arith.all import algdep 

from sage.rings.all import RR, Integer, CC, QQ, RealDoubleElement 

from sage.rings.real_mpfr import create_RealNumber 

 

from sage.misc.latex import latex 

from sage.misc.parser import Parser 

 

from sage.symbolic.ring import var, SR, is_SymbolicVariable 

from sage.symbolic.expression import Expression 

from sage.symbolic.function import Function 

from sage.symbolic.function_factory import function_factory 

from sage.symbolic.integration.integral import (indefinite_integral, 

definite_integral) 

from sage.libs.pynac.pynac import symbol_table 

 

from sage.misc.lazy_import import lazy_import 

lazy_import('sage.interfaces.maxima_lib','maxima') 

 

 

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

def symbolic_sum(expression, v, a, b, algorithm='maxima', hold=False): 

r""" 

Returns the symbolic sum `\sum_{v = a}^b expression` with respect 

to the variable `v` with endpoints `a` and `b`. 

 

INPUT: 

 

- ``expression`` - a symbolic expression 

 

- ``v`` - a variable or variable name 

 

- ``a`` - lower endpoint of the sum 

 

- ``b`` - upper endpoint of the sum 

 

- ``algorithm`` - (default: ``'maxima'``) one of 

 

- ``'maxima'`` - use Maxima (the default) 

 

- ``'maple'`` - (optional) use Maple 

 

- ``'mathematica'`` - (optional) use Mathematica 

 

- ``'giac'`` - (optional) use Giac 

 

- ``'sympy'`` - use SymPy 

 

- ``hold`` - (default: ``False``) if ``True`` don't evaluate 

 

EXAMPLES:: 

 

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

sage: from sage.calculus.calculus import symbolic_sum 

sage: symbolic_sum(k, k, 1, n).factor() 

1/2*(n + 1)*n 

 

:: 

 

sage: symbolic_sum(1/k^4, k, 1, oo) 

1/90*pi^4 

 

:: 

 

sage: symbolic_sum(1/k^5, k, 1, oo) 

zeta(5) 

 

A well known binomial identity:: 

 

sage: symbolic_sum(binomial(n,k), k, 0, n) 

2^n 

 

And some truncations thereof:: 

 

sage: assume(n>1) 

sage: symbolic_sum(binomial(n,k),k,1,n) 

2^n - 1 

sage: symbolic_sum(binomial(n,k),k,2,n) 

2^n - n - 1 

sage: symbolic_sum(binomial(n,k),k,0,n-1) 

2^n - 1 

sage: symbolic_sum(binomial(n,k),k,1,n-1) 

2^n - 2 

 

The binomial theorem:: 

 

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

sage: symbolic_sum(binomial(n,k) * x^k * y^(n-k), k, 0, n) 

(x + y)^n 

 

:: 

 

sage: symbolic_sum(k * binomial(n, k), k, 1, n) 

2^(n - 1)*n 

 

:: 

 

sage: symbolic_sum((-1)^k*binomial(n,k), k, 0, n) 

0 

 

:: 

 

sage: symbolic_sum(2^(-k)/(k*(k+1)), k, 1, oo) 

-log(2) + 1 

 

Summing a hypergeometric term:: 

 

sage: symbolic_sum(binomial(n, k) * factorial(k) / factorial(n+1+k), k, 0, n) 

1/2*sqrt(pi)/factorial(n + 1/2) 

 

We check a well known identity:: 

 

sage: bool(symbolic_sum(k^3, k, 1, n) == symbolic_sum(k, k, 1, n)^2) 

True 

 

A geometric sum:: 

 

sage: a, q = var('a, q') 

sage: symbolic_sum(a*q^k, k, 0, n) 

(a*q^(n + 1) - a)/(q - 1) 

 

For the geometric series, we will have to assume 

the right values for the sum to converge:: 

 

sage: assume(abs(q) < 1) 

sage: symbolic_sum(a*q^k, k, 0, oo) 

-a/(q - 1) 

 

A divergent geometric series. Don't forget 

to forget your assumptions:: 

 

sage: forget() 

sage: assume(q > 1) 

sage: symbolic_sum(a*q^k, k, 0, oo) 

Traceback (most recent call last): 

... 

ValueError: Sum is divergent. 

sage: forget() 

sage: assumptions() # check the assumptions were really forgotten 

[] 

 

This summation only Mathematica can perform:: 

 

sage: symbolic_sum(1/(1+k^2), k, -oo, oo, algorithm = 'mathematica') # optional - mathematica 

pi*coth(pi) 

 

An example of this summation with Giac:: 

 

sage: symbolic_sum(1/(1+k^2), k, -oo, oo, algorithm = 'giac') 

(pi*e^(2*pi) - pi*e^(-2*pi))/(e^(2*pi) + e^(-2*pi) - 2) 

 

SymPy can't solve that summation:: 

 

sage: symbolic_sum(1/(1+k^2), k, -oo, oo, algorithm = 'sympy') 

Traceback (most recent call last): 

... 

AttributeError: Unable to convert SymPy result (=Sum(1/(k**2 + 1), 

(k, -oo, oo))) into Sage 

 

SymPy and Maxima 5.39.0 can do the following (see 

:trac:`22005`):: 

 

sage: sum(1/((2*n+1)^2-4)^2, n, 0, Infinity, algorithm='sympy') 

1/64*pi^2 

sage: sum(1/((2*n+1)^2-4)^2, n, 0, Infinity) 

1/64*pi^2 

 

Use Maple as a backend for summation:: 

 

sage: symbolic_sum(binomial(n,k)*x^k, k, 0, n, algorithm = 'maple') # optional - maple 

(x + 1)^n 

 

If you don't want to evaluate immediately give the ``hold`` keyword:: 

 

sage: s = sum(n, n, 1, k, hold=True); s 

sum(n, n, 1, k) 

sage: s.unhold() 

1/2*k^2 + 1/2*k 

sage: s.subs(k == 10) 

sum(n, n, 1, 10) 

sage: s.subs(k == 10).unhold() 

55 

sage: s.subs(k == 10).n() 

55.0000000000000 

 

TESTS: 

 

:trac:`10564` is fixed:: 

 

sage: sum (n^3 * x^n, n, 0, infinity) 

(x^3 + 4*x^2 + x)/(x^4 - 4*x^3 + 6*x^2 - 4*x + 1) 

 

.. note:: 

 

Sage can currently only understand a subset of the output of Maxima, 

Maple and Mathematica, so even if the chosen backend can perform 

the summation the result might not be convertable into a Sage 

expression. 

""" 

if not is_SymbolicVariable(v): 

if isinstance(v, str): 

v = var(v) 

else: 

raise TypeError("need a summation variable") 

 

if v in SR(a).variables() or v in SR(b).variables(): 

raise ValueError("summation limits must not depend on the summation variable") 

 

if hold: 

from sage.functions.other import symbolic_sum as ssum 

return ssum(expression, v, a, b) 

 

if algorithm == 'maxima': 

return maxima.sr_sum(expression,v,a,b) 

 

elif algorithm == 'mathematica': 

try: 

sum = "Sum[%s, {%s, %s, %s}]" % tuple([repr(expr._mathematica_()) for expr in (expression, v, a, b)]) 

except TypeError: 

raise ValueError("Mathematica cannot make sense of input") 

from sage.interfaces.mathematica import mathematica 

try: 

result = mathematica(sum) 

except TypeError: 

raise ValueError("Mathematica cannot make sense of: %s" % sum) 

return result.sage() 

 

elif algorithm == 'maple': 

sum = "sum(%s, %s=%s..%s)" % tuple([repr(expr._maple_()) for expr in (expression, v, a, b)]) 

from sage.interfaces.maple import maple 

try: 

result = maple(sum).simplify() 

except TypeError: 

raise ValueError("Maple cannot make sense of: %s" % sum) 

return result.sage() 

 

elif algorithm == 'giac': 

sum = "sum(%s, %s, %s, %s)" % tuple([repr(expr._giac_()) for expr in (expression, v, a, b)]) 

from sage.interfaces.giac import giac 

try: 

result = giac(sum) 

except TypeError: 

raise ValueError("Giac cannot make sense of: %s" % sum) 

return result.sage() 

 

elif algorithm == 'sympy': 

expression,v,a,b = [expr._sympy_() for expr in (expression, v, a, b)] 

from sympy import summation 

from sage.interfaces.sympy import sympy_init 

sympy_init() 

result = summation(expression, (v, a, b)) 

try: 

return result._sage_() 

except AttributeError: 

raise AttributeError("Unable to convert SymPy result (={}) into" 

" Sage".format(result)) 

 

else: 

raise ValueError("unknown algorithm: %s" % algorithm) 

 

def nintegral(ex, x, a, b, 

desired_relative_error='1e-8', 

maximum_num_subintervals=200): 

r""" 

Return a floating point machine precision numerical approximation 

to the integral of ``self`` from `a` to 

`b`, computed using floating point arithmetic via maxima. 

 

INPUT: 

 

- ``x`` - variable to integrate with respect to 

 

- ``a`` - lower endpoint of integration 

 

- ``b`` - upper endpoint of integration 

 

- ``desired_relative_error`` - (default: '1e-8') the 

desired relative error 

 

- ``maximum_num_subintervals`` - (default: 200) 

maxima number of subintervals 

 

OUTPUT: 

 

- float: approximation to the integral 

 

- float: estimated absolute error of the 

approximation 

 

- the number of integrand evaluations 

 

- an error code: 

 

- ``0`` - no problems were encountered 

 

- ``1`` - too many subintervals were done 

 

- ``2`` - excessive roundoff error 

 

- ``3`` - extremely bad integrand behavior 

 

- ``4`` - failed to converge 

 

- ``5`` - integral is probably divergent or slowly 

convergent 

 

- ``6`` - the input is invalid; this includes the case of 

desired_relative_error being too small to be achieved 

 

ALIAS: nintegrate is the same as nintegral 

 

REMARK: There is also a function 

``numerical_integral`` that implements numerical 

integration using the GSL C library. It is potentially much faster 

and applies to arbitrary user defined functions. 

 

Also, there are limits to the precision to which Maxima can compute 

the integral due to limitations in quadpack. 

In the following example, remark that the last value of the returned 

tuple is ``6``, indicating that the input was invalid, in this case 

because of a too high desired precision. 

 

:: 

 

sage: f = x 

sage: f.nintegral(x,0,1,1e-14) 

(0.0, 0.0, 0, 6) 

 

EXAMPLES:: 

 

sage: f(x) = exp(-sqrt(x)) 

sage: f.nintegral(x, 0, 1) 

(0.5284822353142306, 4.163...e-11, 231, 0) 

 

We can also use the ``numerical_integral`` function, 

which calls the GSL C library. 

 

:: 

 

sage: numerical_integral(f, 0, 1) 

(0.528482232253147, 6.83928460...e-07) 

 

Note that in exotic cases where floating point evaluation of the 

expression leads to the wrong value, then the output can be 

completely wrong:: 

 

sage: f = exp(pi*sqrt(163)) - 262537412640768744 

 

Despite appearance, `f` is really very close to 0, but one 

gets a nonzero value since the definition of 

``float(f)`` is that it makes all constants inside the 

expression floats, then evaluates each function and each arithmetic 

operation using float arithmetic:: 

 

sage: float(f) 

-480.0 

 

Computing to higher precision we see the truth:: 

 

sage: f.n(200) 

-7.4992740280181431112064614366622348652078895136533593355718e-13 

sage: f.n(300) 

-7.49927402801814311120646143662663009137292462589621789352095066181709095575681963967103004e-13 

 

Now numerically integrating, we see why the answer is wrong:: 

 

sage: f.nintegrate(x,0,1) 

(-480.0000000000001, 5.32907051820075e-12, 21, 0) 

 

It is just because every floating point evaluation of return -480.0 

in floating point. 

 

Important note: using PARI/GP one can compute numerical integrals 

to high precision:: 

 

sage: gp.eval('intnum(x=17,42,exp(-x^2)*log(x))') 

'2.565728500561051474934096410 E-127' # 32-bit 

'2.5657285005610514829176211363206621657 E-127' # 64-bit 

sage: old_prec = gp.set_real_precision(50) 

sage: gp.eval('intnum(x=17,42,exp(-x^2)*log(x))') 

'2.5657285005610514829173563961304957417746108003917 E-127' 

sage: gp.set_real_precision(old_prec) 

57 

 

Note that the input function above is a string in PARI syntax. 

""" 

try: 

v = ex._maxima_().quad_qags(x, a, b, 

epsrel=desired_relative_error, 

limit=maximum_num_subintervals) 

except TypeError as err: 

if "ERROR" in str(err): 

raise ValueError("Maxima (via quadpack) cannot compute the integral") 

else: 

raise TypeError(err) 

 

# Maxima returns unevaluated expressions when the underlying library fails 

# to perfom numerical integration. See: 

# http://www.math.utexas.edu/pipermail/maxima/2008/012975.html 

if 'quad_qags' in str(v): 

raise ValueError("Maxima (via quadpack) cannot compute the integral") 

 

return float(v[0]), float(v[1]), Integer(v[2]), Integer(v[3]) 

 

nintegrate = nintegral 

 

def symbolic_product(expression, v, a, b, algorithm='maxima', hold=False): 

r""" 

Return the symbolic product `\prod_{v = a}^b expression` with respect 

to the variable `v` with endpoints `a` and `b`. 

 

INPUT: 

 

- ``expression`` - a symbolic expression 

 

- ``v`` - a variable or variable name 

 

- ``a`` - lower endpoint of the product 

 

- ``b`` - upper endpoint of the prduct 

 

- ``algorithm`` - (default: ``'maxima'``) one of 

 

- ``'maxima'`` - use Maxima (the default) 

 

- ``'giac'`` - use Giac 

 

- ``'sympy'`` - use SymPy 

 

- ``'mathematica'`` - (optional) use Mathematica 

 

- ``hold`` - (default: ``False``) if ``True`` don't evaluate 

 

EXAMPLES:: 

 

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

sage: from sage.calculus.calculus import symbolic_product 

sage: symbolic_product(k, k, 1, n) 

factorial(n) 

sage: symbolic_product(x + i*(i+1)/2, i, 1, 4) 

x^4 + 20*x^3 + 127*x^2 + 288*x + 180 

sage: symbolic_product(i^2, i, 1, 7) 

25401600 

sage: f = function('f') 

sage: symbolic_product(f(i), i, 1, 7) 

f(7)*f(6)*f(5)*f(4)*f(3)*f(2)*f(1) 

sage: symbolic_product(f(i), i, 1, n) 

product(f(i), i, 1, n) 

sage: assume(k>0) 

sage: symbolic_product(integrate (x^k, x, 0, 1), k, 1, n) 

1/factorial(n + 1) 

sage: symbolic_product(f(i), i, 1, n).log().log_expand() 

sum(log(f(i)), i, 1, n) 

""" 

if not is_SymbolicVariable(v): 

if isinstance(v, str): 

v = var(v) 

else: 

raise TypeError("need a multiplication variable") 

 

if v in SR(a).variables() or v in SR(b).variables(): 

raise ValueError("product limits must not depend on the multiplication variable") 

 

if hold: 

from sage.functions.other import symbolic_product as sprod 

return sprod(expression, v, a, b) 

 

if algorithm == 'maxima': 

return maxima.sr_prod(expression,v,a,b) 

 

elif algorithm == 'mathematica': 

try: 

prod = "Product[%s, {%s, %s, %s}]" % tuple([repr(expr._mathematica_()) for expr in (expression, v, a, b)]) 

except TypeError: 

raise ValueError("Mathematica cannot make sense of input") 

from sage.interfaces.mathematica import mathematica 

try: 

result = mathematica(prod) 

except TypeError: 

raise ValueError("Mathematica cannot make sense of: %s" % sum) 

return result.sage() 

 

elif algorithm == 'giac': 

prod = "product(%s, %s, %s, %s)" % tuple([repr(expr._giac_()) for expr in (expression, v, a, b)]) 

from sage.interfaces.giac import giac 

try: 

result = giac(prod) 

except TypeError: 

raise ValueError("Giac cannot make sense of: %s" % sum) 

return result.sage() 

 

elif algorithm == 'sympy': 

expression,v,a,b = [expr._sympy_() for expr in (expression, v, a, b)] 

from sympy import product as sproduct 

from sage.interfaces.sympy import sympy_init 

sympy_init() 

result = sproduct(expression, (v, a, b)) 

try: 

return result._sage_() 

except AttributeError: 

raise AttributeError("Unable to convert SymPy result (={}) into" 

" Sage".format(result)) 

 

else: 

raise ValueError("unknown algorithm: %s" % algorithm) 

 

 

def minpoly(ex, var='x', algorithm=None, bits=None, degree=None, epsilon=0): 

r""" 

Return the minimal polynomial of self, if possible. 

 

INPUT: 

 

- ``var`` - polynomial variable name (default 'x') 

 

- ``algorithm`` - 'algebraic' or 'numerical' (default 

both, but with numerical first) 

 

- ``bits`` - the number of bits to use in numerical 

approx 

 

- ``degree`` - the expected algebraic degree 

 

- ``epsilon`` - return without error as long as 

f(self) epsilon, in the case that the result cannot be proven. 

 

All of the above parameters are optional, with epsilon=0, bits and 

degree tested up to 1000 and 24 by default respectively. The 

numerical algorithm will be faster if bits and/or degree are given 

explicitly. The algebraic algorithm ignores the last three 

parameters. 

 

 

OUTPUT: The minimal polynomial of self. If the numerical algorithm 

is used then it is proved symbolically when epsilon=0 (default). 

 

If the minimal polynomial could not be found, two distinct kinds of 

errors are raised. If no reasonable candidate was found with the 

given bit/degree parameters, a ``ValueError`` will be 

raised. If a reasonable candidate was found but (perhaps due to 

limits in the underlying symbolic package) was unable to be proved 

correct, a ``NotImplementedError`` will be raised. 

 

ALGORITHM: Two distinct algorithms are used, depending on the 

algorithm parameter. By default, the numerical algorithm is 

attempted first, then the algebraic one. 

 

Algebraic: Attempt to evaluate this expression in QQbar, using 

cyclotomic fields to resolve exponential and trig functions at 

rational multiples of pi, field extensions to handle roots and 

rational exponents, and computing compositums to represent the full 

expression as an element of a number field where the minimal 

polynomial can be computed exactly. The bits, degree, and epsilon 

parameters are ignored. 

 

Numerical: Computes a numerical approximation of 

``self`` and use PARI's algdep to get a candidate 

minpoly `f`. If `f(\mathtt{self})`, 

evaluated to a higher precision, is close enough to 0 then evaluate 

`f(\mathtt{self})` symbolically, attempting to prove 

vanishing. If this fails, and ``epsilon`` is non-zero, 

return `f` if and only if 

`f(\mathtt{self}) < \mathtt{epsilon}`. 

Otherwise raise a ``ValueError`` (if no suitable 

candidate was found) or a ``NotImplementedError`` (if a 

likely candidate was found but could not be proved correct). 

 

EXAMPLES: First some simple examples:: 

 

sage: sqrt(2).minpoly() 

x^2 - 2 

sage: minpoly(2^(1/3)) 

x^3 - 2 

sage: minpoly(sqrt(2) + sqrt(-1)) 

x^4 - 2*x^2 + 9 

sage: minpoly(sqrt(2)-3^(1/3)) 

x^6 - 6*x^4 + 6*x^3 + 12*x^2 + 36*x + 1 

 

 

Works with trig and exponential functions too. 

 

:: 

 

sage: sin(pi/3).minpoly() 

x^2 - 3/4 

sage: sin(pi/7).minpoly() 

x^6 - 7/4*x^4 + 7/8*x^2 - 7/64 

sage: minpoly(exp(I*pi/17)) 

x^16 - x^15 + x^14 - x^13 + x^12 - x^11 + x^10 - x^9 + x^8 - x^7 + x^6 - x^5 + x^4 - x^3 + x^2 - x + 1 

 

Here we verify it gives the same result as the abstract number 

field. 

 

:: 

 

sage: (sqrt(2) + sqrt(3) + sqrt(6)).minpoly() 

x^4 - 22*x^2 - 48*x - 23 

sage: K.<a,b> = NumberField([x^2-2, x^2-3]) 

sage: (a+b+a*b).absolute_minpoly() 

x^4 - 22*x^2 - 48*x - 23 

 

The minpoly function is used implicitly when creating 

number fields:: 

 

sage: x = var('x') 

sage: eqn = x^3 + sqrt(2)*x + 5 == 0 

sage: a = solve(eqn, x)[0].rhs() 

sage: QQ[a] 

Number Field in a with defining polynomial x^6 + 10*x^3 - 2*x^2 + 25 

 

Here we solve a cubic and then recover it from its complicated 

radical expansion. 

 

:: 

 

sage: f = x^3 - x + 1 

sage: a = f.solve(x)[0].rhs(); a 

-1/2*(1/18*sqrt(23)*sqrt(3) - 1/2)^(1/3)*(I*sqrt(3) + 1) - 1/6*(-I*sqrt(3) + 1)/(1/18*sqrt(23)*sqrt(3) - 1/2)^(1/3) 

sage: a.minpoly() 

x^3 - x + 1 

 

Note that simplification may be necessary to see that the minimal 

polynomial is correct. 

 

:: 

 

sage: a = sqrt(2)+sqrt(3)+sqrt(5) 

sage: f = a.minpoly(); f 

x^8 - 40*x^6 + 352*x^4 - 960*x^2 + 576 

sage: f(a) 

(sqrt(5) + sqrt(3) + sqrt(2))^8 - 40*(sqrt(5) + sqrt(3) + sqrt(2))^6 + 352*(sqrt(5) + sqrt(3) + sqrt(2))^4 - 960*(sqrt(5) + sqrt(3) + sqrt(2))^2 + 576 

sage: f(a).expand() 

0 

 

:: 

 

sage: a = sin(pi/7) 

sage: f = a.minpoly(algorithm='numerical'); f 

x^6 - 7/4*x^4 + 7/8*x^2 - 7/64 

sage: f(a).horner(a).numerical_approx(100) 

0.00000000000000000000000000000 

 

The degree must be high enough (default tops out at 24). 

 

:: 

 

sage: a = sqrt(3) + sqrt(2) 

sage: a.minpoly(algorithm='numerical', bits=100, degree=3) 

Traceback (most recent call last): 

... 

ValueError: Could not find minimal polynomial (100 bits, degree 3). 

sage: a.minpoly(algorithm='numerical', bits=100, degree=10) 

x^4 - 10*x^2 + 1 

 

:: 

 

sage: cos(pi/33).minpoly(algorithm='algebraic') 

x^10 + 1/2*x^9 - 5/2*x^8 - 5/4*x^7 + 17/8*x^6 + 17/16*x^5 - 43/64*x^4 - 43/128*x^3 + 3/64*x^2 + 3/128*x + 1/1024 

sage: cos(pi/33).minpoly(algorithm='numerical') 

x^10 + 1/2*x^9 - 5/2*x^8 - 5/4*x^7 + 17/8*x^6 + 17/16*x^5 - 43/64*x^4 - 43/128*x^3 + 3/64*x^2 + 3/128*x + 1/1024 

 

Sometimes it fails, as it must given that some numbers aren't algebraic:: 

 

sage: sin(1).minpoly(algorithm='numerical') 

Traceback (most recent call last): 

... 

ValueError: Could not find minimal polynomial (1000 bits, degree 24). 

 

.. note:: 

 

Of course, failure to produce a minimal polynomial does not 

necessarily indicate that this number is transcendental. 

""" 

if algorithm is None or algorithm.startswith('numeric'): 

bits_list = [bits] if bits else [100,200,500,1000] 

degree_list = [degree] if degree else [2,4,8,12,24] 

 

for bits in bits_list: 

a = ex.numerical_approx(bits) 

check_bits = int(1.25 * bits + 80) 

aa = ex.numerical_approx(check_bits) 

 

for degree in degree_list: 

 

f = QQ[var](algdep(a, degree)) # TODO: use the known_bits parameter? 

# If indeed we have found a minimal polynomial, 

# it should be accurate to a much higher precision. 

error = abs(f(aa)) 

dx = ~RR(Integer(1) << (check_bits - degree - 2)) 

expected_error = abs(f.derivative()(CC(aa))) * dx 

 

if error < expected_error: 

# Degree might have been an over-estimate, 

# factor because we want (irreducible) minpoly. 

ff = f.factor() 

for g, e in ff: 

lead = g.leading_coefficient() 

if lead != 1: 

g = g / lead 

expected_error = abs(g.derivative()(CC(aa))) * dx 

error = abs(g(aa)) 

if error < expected_error: 

# See if we can prove equality exactly 

if g(ex).simplify_trig().canonicalize_radical() == 0: 

return g 

# Otherwise fall back to numerical guess 

elif epsilon and error < epsilon: 

return g 

elif algorithm is not None: 

raise NotImplementedError("Could not prove minimal polynomial %s (epsilon %s)" % (g, RR(error).str(no_sci=False))) 

 

if algorithm is not None: 

raise ValueError("Could not find minimal polynomial (%s bits, degree %s)." % (bits, degree)) 

 

if algorithm is None or algorithm == 'algebraic': 

from sage.rings.all import QQbar 

return QQ[var](QQbar(ex).minpoly()) 

 

raise ValueError("Unknown algorithm: %s" % algorithm) 

 

 

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

# limits 

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

def limit(ex, dir=None, taylor=False, algorithm='maxima', **argv): 

r""" 

Return the limit as the variable `v` approaches `a` 

from the given direction. 

 

:: 

 

expr.limit(x = a) 

expr.limit(x = a, dir='+') 

 

INPUT: 

 

- ``dir`` - (default: None); dir may have the value 

'plus' (or '+' or 'right' or 'above') for a limit from above, 

'minus' (or '-' or 'left' or 'below') for a limit from below, or may be omitted 

(implying a two-sided limit is to be computed). 

 

- ``taylor`` - (default: False); if True, use Taylor 

series, which allows more limits to be computed (but may also 

crash in some obscure cases due to bugs in Maxima). 

 

- ``**argv`` - 1 named parameter 

 

.. note:: 

 

The output may also use 'und' (undefined), 'ind' 

(indefinite but bounded), and 'infinity' (complex 

infinity). 

 

EXAMPLES:: 

 

sage: x = var('x') 

sage: f = (1+1/x)^x 

sage: f.limit(x = oo) 

e 

sage: f.limit(x = 5) 

7776/3125 

sage: f.limit(x = 1.2) 

2.06961575467... 

sage: f.limit(x = I, taylor=True) 

(-I + 1)^I 

sage: f(x=1.2) 

2.0696157546720... 

sage: f(x=I) 

(-I + 1)^I 

sage: CDF(f(x=I)) 

2.0628722350809046 + 0.7450070621797239*I 

sage: CDF(f.limit(x = I)) 

2.0628722350809046 + 0.7450070621797239*I 

 

Notice that Maxima may ask for more information:: 

 

sage: var('a') 

a 

sage: limit(x^a,x=0) 

Traceback (most recent call last): 

... 

ValueError: Computation failed since Maxima requested additional 

constraints; using the 'assume' command before evaluation 

*may* help (example of legal syntax is 'assume(a>0)', see 

`assume?` for more details) 

Is a positive, negative or zero? 

 

With this example, Maxima is looking for a LOT of information:: 

 

sage: assume(a>0) 

sage: limit(x^a,x=0) 

Traceback (most recent call last): 

... 

ValueError: Computation failed since Maxima requested additional 

constraints; using the 'assume' command before evaluation *may* help 

(example of legal syntax is 'assume(a>0)', see `assume?` for 

more details) 

Is a an integer? 

sage: assume(a,'integer') 

sage: limit(x^a,x=0) 

Traceback (most recent call last): 

... 

ValueError: Computation failed since Maxima requested additional 

constraints; using the 'assume' command before evaluation *may* help 

(example of legal syntax is 'assume(a>0)', see `assume?` for 

more details) 

Is a an even number? 

sage: assume(a,'even') 

sage: limit(x^a,x=0) 

0 

sage: forget() 

 

More examples:: 

 

sage: limit(x*log(x), x = 0, dir='+') 

0 

sage: lim((x+1)^(1/x), x = 0) 

e 

sage: lim(e^x/x, x = oo) 

+Infinity 

sage: lim(e^x/x, x = -oo) 

0 

sage: lim(-e^x/x, x = oo) 

-Infinity 

sage: lim((cos(x))/(x^2), x = 0) 

+Infinity 

sage: lim(sqrt(x^2+1) - x, x = oo) 

0 

sage: lim(x^2/(sec(x)-1), x=0) 

2 

sage: lim(cos(x)/(cos(x)-1), x=0) 

-Infinity 

sage: lim(x*sin(1/x), x=0) 

0 

sage: limit(e^(-1/x), x=0, dir='right') 

0 

sage: limit(e^(-1/x), x=0, dir='left') 

+Infinity 

 

:: 

 

sage: f = log(log(x))/log(x) 

sage: forget(); assume(x<-2); lim(f, x=0, taylor=True) 

0 

sage: forget() 

 

Here ind means "indefinite but bounded":: 

 

sage: lim(sin(1/x), x = 0) 

ind 

 

TESTS:: 

 

sage: lim(x^2, x=2, dir='nugget') 

Traceback (most recent call last): 

... 

ValueError: dir must be one of None, 'plus', '+', 'above', 'right', 

'minus', '-', 'below', 'left' 

 

We check that :trac:`3718` is fixed, so that 

Maxima gives correct limits for the floor function:: 

 

sage: limit(floor(x), x=0, dir='-') 

-1 

sage: limit(floor(x), x=0, dir='+') 

0 

sage: limit(floor(x), x=0) 

und 

 

Maxima gives the right answer here, too, showing 

that :trac:`4142` is fixed:: 

 

sage: f = sqrt(1-x^2) 

sage: g = diff(f, x); g 

-x/sqrt(-x^2 + 1) 

sage: limit(g, x=1, dir='-') 

-Infinity 

 

:: 

 

sage: limit(1/x, x=0) 

Infinity 

sage: limit(1/x, x=0, dir='+') 

+Infinity 

sage: limit(1/x, x=0, dir='-') 

-Infinity 

 

Check that :trac:`8942` is fixed:: 

 

sage: f(x) = (cos(pi/4-x) - tan(x)) / (1 - sin(pi/4+x)) 

sage: limit(f(x), x = pi/4, dir='minus') 

+Infinity 

sage: limit(f(x), x = pi/4, dir='plus') 

-Infinity 

sage: limit(f(x), x = pi/4) 

Infinity 

 

Check that :trac:`12708` is fixed:: 

 

sage: limit(tanh(x),x=0) 

0 

 

Check that :trac:`15386` is fixed:: 

 

sage: n = var('n') 

sage: assume(n>0) 

sage: sequence = -(3*n^2 + 1)*(-1)^n/sqrt(n^5 + 8*n^3 + 8) 

sage: limit(sequence, n=infinity) 

0 

 

Check if :trac:`23048` is fixed:: 

 

sage: (1/(x-3)).limit(x=3, dir='below') 

-Infinity 

""" 

if not isinstance(ex, Expression): 

ex = SR(ex) 

 

if len(argv) != 1: 

raise ValueError("call the limit function like this, e.g. limit(expr, x=2).") 

else: 

k, = argv.keys() 

v = var(k) 

a = argv[k] 

 

if taylor and algorithm == 'maxima': 

algorithm = 'maxima_taylor' 

 

if dir not in [None, 'plus', '+', 'right', 'minus', '-', 'left', 

'above', 'below']: 

raise ValueError("dir must be one of None, 'plus', '+', 'above', 'right', 'minus', '-', 'below', 'left'") 

 

if algorithm == 'maxima': 

if dir is None: 

l = maxima.sr_limit(ex, v, a) 

elif dir in ['plus', '+', 'right', 'above']: 

l = maxima.sr_limit(ex, v, a, 'plus') 

elif dir in ['minus', '-', 'left', 'below']: 

l = maxima.sr_limit(ex, v, a, 'minus') 

elif algorithm == 'maxima_taylor': 

if dir is None: 

l = maxima.sr_tlimit(ex, v, a) 

elif dir in ['plus', '+', 'right', 'above']: 

l = maxima.sr_tlimit(ex, v, a, 'plus') 

elif dir in ['minus', '-', 'left', 'below']: 

l = maxima.sr_tlimit(ex, v, a, 'minus') 

elif algorithm == 'sympy': 

if dir is None: 

import sympy 

l = sympy.limit(ex._sympy_(), v._sympy_(), a._sympy_()) 

else: 

raise NotImplementedError("sympy does not support one-sided limits") 

 

#return l.sage() 

return ex.parent()(l) 

 

# lim is alias for limit 

lim = limit 

 

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

# Laplace transform 

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

def laplace(ex, t, s, algorithm='maxima'): 

r""" 

Return the Laplace transform with respect to the variable `t` and  

transform parameter `s`, if possible. 

 

If this function cannot find a solution, a formal function is returned.  

The function that is returned may be viewed as a function of `s`. 

 

DEFINITION: 

 

The Laplace transform of a function `f(t)`, defined for all real numbers  

`t \geq 0`, is the function `F(s)` defined by 

 

.. MATH:: 

 

F(s) = \int_{0}^{\infty} e^{-st} f(t) dt. 

 

INPUT: 

 

- ``ex`` - a symbolic expression 

 

- ``t`` - independent variable 

 

- ``s`` - transform parameter 

 

- ``algorithm`` - (default: ``'maxima'``) one of 

 

- ``'maxima'`` - use Maxima (the default) 

 

- ``'sympy'`` - use SymPy 

 

- ``'giac'`` - use Giac 

 

NOTES: 

 

- The ``'sympy'`` algorithm returns the tuple (`F`, `a`, ``cond``) where `F` is the Laplace  

transform of `f(t)`, `Re(s)>a` is the half-plane of convergence, and cond  

are auxiliary convergence conditions. 

 

.. SEEALSO:: 

 

:func:`inverse_laplace` 

 

EXAMPLES: 

 

We compute a few Laplace transforms:: 

 

sage: var('x, s, z, t, t0') 

(x, s, z, t, t0) 

sage: sin(x).laplace(x, s) 

1/(s^2 + 1) 

sage: (z + exp(x)).laplace(x, s) 

z/s + 1/(s - 1) 

sage: log(t/t0).laplace(t, s) 

-(euler_gamma + log(s) + log(t0))/s 

 

We do a formal calculation:: 

 

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

sage: g = f.diff(x); g 

diff(f(x), x) 

sage: g.laplace(x, s) 

s*laplace(f(x), x, s) - f(0) 

 

A BATTLE BETWEEN the X-women and the Y-men (by David 

Joyner): Solve 

 

.. MATH:: 

 

x' = -16y, x(0)=270, y' = -x + 1, y(0) = 90. 

 

This models a fight between two sides, the "X-women" and the 

"Y-men", where the X-women have 270 initially and the Y-men have 

90, but the Y-men are better at fighting, because of the higher 

factor of "-16" vs "-1", and also get an occasional reinforcement, 

because of the "+1" term. 

 

:: 

 

sage: var('t') 

t 

sage: t = var('t') 

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

sage: y = function('y')(t) 

sage: de1 = x.diff(t) + 16*y 

sage: de2 = y.diff(t) + x - 1 

sage: de1.laplace(t, s) 

s*laplace(x(t), t, s) + 16*laplace(y(t), t, s) - x(0) 

sage: de2.laplace(t, s) 

s*laplace(y(t), t, s) - 1/s + laplace(x(t), t, s) - y(0) 

 

Next we form the augmented matrix of the above system:: 

 

sage: A = matrix([[s, 16, 270],[1, s, 90+1/s]]) 

sage: E = A.echelon_form() 

sage: xt = E[0,2].inverse_laplace(s,t) 

sage: yt = E[1,2].inverse_laplace(s,t) 

sage: xt 

-91/2*e^(4*t) + 629/2*e^(-4*t) + 1 

sage: yt 

91/8*e^(4*t) + 629/8*e^(-4*t) 

sage: p1 = plot(xt,0,1/2,rgbcolor=(1,0,0)) 

sage: p2 = plot(yt,0,1/2,rgbcolor=(0,1,0)) 

sage: (p1+p2).save(os.path.join(SAGE_TMP, "de_plot.png")) 

 

Another example:: 

 

sage: var('a,s,t') 

(a, s, t) 

sage: f = exp (2*t + a) * sin(t) * t; f 

t*e^(a + 2*t)*sin(t) 

sage: L = laplace(f, t, s); L 

2*(s - 2)*e^a/(s^2 - 4*s + 5)^2 

sage: inverse_laplace(L, s, t) 

t*e^(a + 2*t)*sin(t) 

 

Unable to compute solution with Maxima:: 

 

sage: laplace(heaviside(t-1), t, s) 

laplace(heaviside(t - 1), t, s) 

 

Heaviside step function can be handled with different interfaces.  

Try with giac:: 

 

sage: laplace(heaviside(t-1), t, s, algorithm='giac') 

e^(-s)/s 

 

Try with SymPy:: 

 

sage: laplace(heaviside(t-1), t, s, algorithm='sympy') 

(e^(-s)/s, 0, True)  

 

TESTS: 

 

Testing Giac:: 

 

sage: var('t, s') 

(t, s) 

sage: laplace(5*cos(3*t-2)*heaviside(t-2), t, s, algorithm='giac') 

5*(s*cos(4)*e^(-2*s) - 3*e^(-2*s)*sin(4))/(s^2 + 9) 

 

Check unevaluated expression from Giac (it is locale-dependent, see 

:trac:`22833`):: 

 

sage: var('n') 

n 

sage: laplace(t^n, t, s, algorithm='giac') 

laplace(t^n, t, s) 

 

Testing SymPy:: 

 

sage: laplace(t^n, t, s, algorithm='sympy') 

(s^(-n)*gamma(n + 1)/s, 0, -re(n) < 1) 

 

Testing Maxima:: 

 

sage: laplace(t^n, t, s, algorithm='maxima') 

s^(-n - 1)*gamma(n + 1)  

 

Testing expression that is not parsed from SymPy to Sage:: 

 

sage: laplace(cos(t^2), t, s, algorithm='sympy') 

Traceback (most recent call last): 

... 

AttributeError: Unable to convert SymPy result (=sqrt(pi)*(sqrt(2)*sin(s**2/4)*fresnelc(sqrt(2)*s/(2*sqrt(pi))) -  

sqrt(2)*cos(s**2/4)*fresnels(sqrt(2)*s/(2*sqrt(pi))) + cos(s**2/4 + pi/4))/2) into Sage 

""" 

if not isinstance(ex, (Expression, Function)): 

ex = SR(ex) 

 

if algorithm == 'maxima': 

return ex.parent()(ex._maxima_().laplace(var(t), var(s))) 

 

elif algorithm == 'sympy': 

ex_sy, t, s = [expr._sympy_() for expr in (ex, t, s)] 

from sympy import laplace_transform 

from sage.interfaces.sympy import sympy_init 

sympy_init() 

result = laplace_transform(ex_sy, t, s) 

if isinstance(result, tuple): 

try: 

(result, a, cond) = result 

return result._sage_(), a, cond 

except AttributeError: 

raise AttributeError("Unable to convert SymPy result (={}) into" 

" Sage".format(result)) 

elif 'LaplaceTransform' in format(result): 

return dummy_laplace(ex, t, s) 

else: 

return result 

 

elif algorithm == 'giac': 

from sage.interfaces.giac import giac 

try: 

result = giac.laplace(ex, t, s) 

except TypeError: 

raise ValueError("Giac cannot make sense of: %s" % ex_gi) 

if 'integrate' in format(result) or 'integration' in format(result): 

return dummy_laplace(ex, t, s) 

else: 

return result.sage() 

 

else: 

raise ValueError("Unknown algorithm: %s" % algorithm) 

 

def inverse_laplace(ex, s, t, algorithm='maxima'): 

r""" 

Return the inverse Laplace transform with respect to the variable `t` and  

transform parameter `s`, if possible. 

 

If this function cannot find a solution, a formal function is returned.  

The function that is returned may be viewed as a function of `t`. 

 

DEFINITION:  

 

The inverse Laplace transform of a function `F(s)` is the function  

`f(t)`, defined by 

 

.. MATH:: 

 

F(s) = \frac{1}{2\pi i} \int_{\gamma-i\infty}^{\gamma + i\infty} e^{st} F(s) dt, 

 

where `\gamma` is chosen so that the contour path of 

integration is in the region of convergence of `F(s)`. 

 

INPUT: 

 

- ``ex`` - a symbolic expression 

 

- ``s`` - transform parameter 

 

- ``t`` - independent variable 

 

- ``algorithm`` - (default: ``'maxima'``) one of 

 

- ``'maxima'`` - use Maxima (the default) 

 

- ``'sympy'`` - use SymPy 

 

- ``'giac'`` - use Giac 

 

.. SEEALSO:: 

 

:func:`laplace` 

 

EXAMPLES:: 

 

sage: var('w, m') 

(w, m) 

sage: f = (1/(w^2+10)).inverse_laplace(w, m); f 

1/10*sqrt(10)*sin(sqrt(10)*m) 

sage: laplace(f, m, w) 

1/(w^2 + 10) 

 

sage: f(t) = t*cos(t) 

sage: s = var('s') 

sage: L = laplace(f, t, s); L 

t |--> 2*s^2/(s^2 + 1)^2 - 1/(s^2 + 1) 

sage: inverse_laplace(L, s, t) 

t |--> t*cos(t) 

sage: inverse_laplace(1/(s^3+1), s, t) 

1/3*(sqrt(3)*sin(1/2*sqrt(3)*t) - cos(1/2*sqrt(3)*t))*e^(1/2*t) + 1/3*e^(-t) 

 

No explicit inverse Laplace transform, so one is returned formally a  

function ``ilt``:: 

 

sage: inverse_laplace(cos(s), s, t) 

ilt(cos(s), s, t) 

 

Transform an expression involving a time-shift, via SymPy:: 

 

sage: inverse_laplace(1/s^2*exp(-s), s, t, algorithm='sympy') 

-(log(e^(-t)) + 1)*heaviside(t - 1) 

 

The same instance with Giac:: 

 

sage: inverse_laplace(1/s^2*exp(-s), s, t, algorithm='giac') 

(t - 1)*heaviside(t - 1) 

 

Transform a rational expression:: 

 

sage: inverse_laplace((2*s^2*exp(-2*s) - exp(-s))/(s^3+1), s, t, algorithm='giac') 

-1/3*(sqrt(3)*e^(1/2*t - 1/2)*sin(1/2*sqrt(3)*(t - 1)) - cos(1/2*sqrt(3)*(t - 1))*e^(1/2*t - 1/2) +  

e^(-t + 1))*heaviside(t - 1) + 2/3*(2*cos(1/2*sqrt(3)*(t - 2))*e^(1/2*t - 1) + e^(-t + 2))*heaviside(t - 2) 

 

Dirac delta function can also be handled:: 

 

sage: inverse_laplace(1, s, t, algorithm='giac') 

dirac_delta(t) 

 

TESTS: 

 

Testing unevaluated expression from Maxima:: 

 

sage: var('t, s') 

(t, s) 

sage: inverse_laplace(exp(-s)/s, s, t) 

ilt(e^(-s)/s, s, t) 

 

Testing Giac:: 

 

sage: inverse_laplace(exp(-s)/s, s, t, algorithm='giac') 

heaviside(t - 1) 

 

Testing SymPy:: 

 

sage: inverse_laplace(exp(-s)/s, s, t, algorithm='sympy') 

heaviside(t - 1)  

 

Testing unevaluated expression from Giac:: 

 

sage: n = var('n') 

sage: inverse_laplace(1/s^n, s, t, algorithm='giac') 

ilt(1/(s^n), t, s) 

 

Try with Maxima:: 

 

sage: inverse_laplace(1/s^n, s, t, algorithm='maxima') 

ilt(1/(s^n), s, t) 

 

Try with SymPy:: 

 

sage: inverse_laplace(1/s^n, s, t, algorithm='sympy') 

t^(n - 1)*heaviside(t)/gamma(n) 

 

Testing unevaluated expression from SymPy:: 

 

sage: inverse_laplace(cos(s), s, t, algorithm='sympy') 

ilt(cos(s), t, s) 

 

Testing the same with Giac:: 

 

sage: inverse_laplace(cos(s), s, t, algorithm='giac') 

ilt(cos(s), t, s) 

""" 

if not isinstance(ex, Expression): 

ex = SR(ex) 

 

if algorithm == 'maxima': 

return ex.parent()(ex._maxima_().ilt(var(s), var(t))) 

 

elif algorithm == 'sympy': 

ex_sy, s, t = [expr._sympy_() for expr in (ex, s, t)] 

from sympy import inverse_laplace_transform 

from sage.interfaces.sympy import sympy_init 

sympy_init() 

result = inverse_laplace_transform(ex_sy, s, t) 

try: 

return result._sage_() 

except AttributeError: 

if 'InverseLaplaceTransform' in format(result): 

return dummy_inverse_laplace(ex, t, s) 

else: 

raise AttributeError("Unable to convert SymPy result (={}) into" 

" Sage".format(result)) 

 

elif algorithm == 'giac': 

from sage.interfaces.giac import giac 

try: 

result = giac.invlaplace(ex, s, t) 

except TypeError: 

raise ValueError("Giac cannot make sense of: %s" % ex) 

if 'ilaplace' in format(result): 

return dummy_inverse_laplace(ex, t, s) 

else: 

return result.sage() 

 

else: 

raise ValueError("Unknown algorithm: %s" % algorithm) 

 

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

# symbolic evaluation "at" a point 

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

def at(ex, *args, **kwds): 

""" 

Parses ``at`` formulations from other systems, such as Maxima. 

Replaces evaluation 'at' a point with substitution method of 

a symbolic expression. 

 

EXAMPLES: 

 

We do not import ``at`` at the top level, but we can use it 

as a synonym for substitution if we import it:: 

 

sage: g = x^3-3 

sage: from sage.calculus.calculus import at 

sage: at(g, x=1) 

-2 

sage: g.subs(x=1) 

-2 

 

We find a formal Taylor expansion:: 

 

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

sage: u = function('u') 

sage: u(x + h) 

u(h + x) 

sage: diff(u(x+h), x) 

D[0](u)(h + x) 

sage: taylor(u(x+h),h,0,4) 

1/24*h^4*diff(u(x), x, x, x, x) + 1/6*h^3*diff(u(x), x, x, x) + 1/2*h^2*diff(u(x), x, x) + h*diff(u(x), x) + u(x) 

 

We compute a Laplace transform:: 

 

sage: var('s,t') 

(s, t) 

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

sage: f.diff(t,2) 

diff(f(t), t, t) 

sage: f.diff(t,2).laplace(t,s) 

s^2*laplace(f(t), t, s) - s*f(0) - D[0](f)(0) 

 

We can also accept a non-keyword list of expression substitutions, 

like Maxima does (:trac:`12796`):: 

 

sage: from sage.calculus.calculus import at 

sage: f = function('f') 

sage: at(f(x), [x == 1]) 

f(1) 

 

TESTS: 

 

Our one non-keyword argument must be a list:: 

 

sage: from sage.calculus.calculus import at 

sage: f = function('f') 

sage: at(f(x), x == 1) 

Traceback (most recent call last): 

... 

TypeError: at can take at most one argument, which must be a list 

 

We should convert our first argument to a symbolic expression:: 

 

sage: from sage.calculus.calculus import at 

sage: at(int(1), x=1) 

1 

 

""" 

if not isinstance(ex, (Expression, Function)): 

ex = SR(ex) 

kwds={ (k[10:] if k[:10] == "_SAGE_VAR_" else k):v for k,v in six.iteritems(kwds)} 

if len(args) == 1 and isinstance(args[0],list): 

for c in args[0]: 

kwds[str(c.lhs())]=c.rhs() 

else: 

if len(args) !=0: 

raise TypeError("at can take at most one argument, which must be a list") 

 

return ex.subs(**kwds) 

 

def dummy_diff(*args): 

""" 

This function is called when 'diff' appears in a Maxima string. 

 

EXAMPLES:: 

 

sage: from sage.calculus.calculus import dummy_diff 

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

sage: dummy_diff(sin(x*y), x, SR(2), y, SR(1)) 

-x*y^2*cos(x*y) - 2*y*sin(x*y) 

 

Here the function is used implicitly:: 

 

sage: a = var('a') 

sage: f = function('cr')(a) 

sage: g = f.diff(a); g 

diff(cr(a), a) 

""" 

f = args[0] 

args = list(args[1:]) 

for i in range(1, len(args), 2): 

args[i] = Integer(args[i]) 

return f.diff(*args) 

 

def dummy_integrate(*args): 

""" 

This function is called to create formal wrappers of integrals that 

Maxima can't compute: 

 

EXAMPLES:: 

 

sage: from sage.calculus.calculus import dummy_integrate 

sage: f = function('f') 

sage: dummy_integrate(f(x), x) 

integrate(f(x), x) 

sage: a,b = var('a,b') 

sage: dummy_integrate(f(x), x, a, b) 

integrate(f(x), x, a, b) 

""" 

if len(args) == 4: 

return definite_integral(*args, hold=True) 

else: 

return indefinite_integral(*args, hold=True) 

 

def dummy_laplace(*args): 

""" 

This function is called to create formal wrappers of laplace transforms 

that Maxima can't compute: 

 

EXAMPLES:: 

 

sage: from sage.calculus.calculus import dummy_laplace 

sage: s,t = var('s,t') 

sage: f = function('f') 

sage: dummy_laplace(f(t),t,s) 

laplace(f(t), t, s) 

""" 

return _laplace(args[0], var(repr(args[1])), var(repr(args[2]))) 

 

def dummy_inverse_laplace(*args): 

""" 

This function is called to create formal wrappers of inverse laplace 

transforms that Maxima can't compute: 

 

EXAMPLES:: 

 

sage: from sage.calculus.calculus import dummy_inverse_laplace 

sage: s,t = var('s,t') 

sage: F = function('F') 

sage: dummy_inverse_laplace(F(s),s,t) 

ilt(F(s), s, t) 

""" 

return _inverse_laplace(args[0], var(repr(args[1])), var(repr(args[2]))) 

 

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

# 

# Helper functions for printing latex expression 

# 

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

 

def _laplace_latex_(self, *args): 

r""" 

Return LaTeX expression for Laplace transform of a symbolic function. 

 

EXAMPLES:: 

 

sage: from sage.calculus.calculus import _laplace_latex_ 

sage: var('s,t') 

(s, t) 

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

sage: _laplace_latex_(0,f,t,s) 

'\\mathcal{L}\\left(f\\left(t\\right), t, s\\right)' 

sage: latex(laplace(f, t, s)) 

\mathcal{L}\left(f\left(t\right), t, s\right) 

 

""" 

return "\\mathcal{L}\\left(%s\\right)"%(', '.join([latex(x) for x in args])) 

 

def _inverse_laplace_latex_(self, *args): 

r""" 

Return LaTeX expression for inverse Laplace transform 

of a symbolic function. 

 

EXAMPLES:: 

 

sage: from sage.calculus.calculus import _inverse_laplace_latex_ 

sage: var('s,t') 

(s, t) 

sage: F = function('F')(s) 

sage: _inverse_laplace_latex_(0,F,s,t) 

'\\mathcal{L}^{-1}\\left(F\\left(s\\right), s, t\\right)' 

sage: latex(inverse_laplace(F,s,t)) 

\mathcal{L}^{-1}\left(F\left(s\right), s, t\right) 

""" 

return "\\mathcal{L}^{-1}\\left(%s\\right)"%(', '.join([latex(x) for x in args])) 

 

# Return un-evaluated expression as instances of SFunction class 

_laplace = function_factory('laplace', print_latex_func=_laplace_latex_) 

_inverse_laplace = function_factory('ilt', 

print_latex_func=_inverse_laplace_latex_) 

 

######################################i################ 

 

 

 

 

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

 

# Conversion dict for special maxima objects 

# c,k1,k2 are from ode2() 

symtable = {'%pi':'pi', '%e': 'e', '%i':'I', '%gamma':'euler_gamma',\ 

'%c' : '_C', '%k1' : '_K1', '%k2' : '_K2', 

'e':'_e', 'i':'_i', 'I':'_I'} 

 

import re 

 

import six 

 

 

maxima_tick = re.compile("'[a-z|A-Z|0-9|_]*") 

 

maxima_qp = re.compile("\?\%[a-z|A-Z|0-9|_]*") # e.g., ?%jacobi_cd 

 

maxima_var = re.compile("[a-z|A-Z|0-9|_\%]*") # e.g., %jacobi_cd 

 

sci_not = re.compile("(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]\d+)") 

 

polylog_ex = re.compile('li\[([^\[\]]*)\]\(') 

 

maxima_polygamma = re.compile("psi\[([^\[\]]*)\]\(") # matches psi[n]( where n is a number 

 

maxima_hyper = re.compile("\%f\[\d+,\d+\]") # matches %f[m,n] 

 

def symbolic_expression_from_maxima_string(x, equals_sub=False, maxima=maxima): 

""" 

Given a string representation of a Maxima expression, parse it and 

return the corresponding Sage symbolic expression. 

 

INPUT: 

 

- ``x`` - a string 

 

- ``equals_sub`` - (default: False) if True, replace 

'=' by '==' in self 

 

- ``maxima`` - (default: the calculus package's 

Maxima) the Maxima interpreter to use. 

 

EXAMPLES:: 

 

sage: from sage.calculus.calculus import symbolic_expression_from_maxima_string as sefms 

sage: sefms('x^%e + %e^%pi + %i + sin(0)') 

x^e + e^pi + I 

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

sage: sefms('?%at(f(x),x=2)#1') 

f(2) != 1 

sage: a = sage.calculus.calculus.maxima("x#0"); a 

x#0 

sage: a.sage() 

x != 0 

 

TESTS: 

 

:trac:`8459` fixed:: 

 

sage: maxima('3*li[2](u)+8*li[33](exp(u))').sage() 

3*dilog(u) + 8*polylog(33, e^u) 

 

Check if :trac:`8345` is fixed:: 

 

sage: assume(x,'complex') 

sage: t = x.conjugate() 

sage: latex(t) 

\overline{x} 

sage: latex(t._maxima_()._sage_()) 

\overline{x} 

 

Check that we can understand maxima's not-equals (:trac:`8969`):: 

 

sage: from sage.calculus.calculus import symbolic_expression_from_maxima_string as sefms 

sage: sefms("x!=3") == (factorial(x) == 3) 

True 

sage: sefms("x # 3") == SR(x != 3) 

True 

sage: solve([x != 5], x) 

#0: solve_rat_ineq(ineq=_SAGE_VAR_x # 5) 

[[x - 5 != 0]] 

sage: solve([2*x==3, x != 5], x) 

[[x == (3/2), (-7/2) != 0]] 

 

Make sure that we don't accidentally pick up variables in the maxima namespace (:trac:`8734`):: 

 

sage: sage.calculus.calculus.maxima('my_new_var : 2') 

2 

sage: var('my_new_var').full_simplify() 

my_new_var 

 

ODE solution constants are treated differently (:trac:`16007`):: 

 

sage: from sage.calculus.calculus import symbolic_expression_from_maxima_string as sefms 

sage: sefms('%k1*x + %k2*y + %c') 

_K1*x + _K2*y + _C 

 

Check that some hypothetical variables don't end up as special constants (:trac:`6882`):: 

 

sage: from sage.calculus.calculus import symbolic_expression_from_maxima_string as sefms 

sage: sefms('%i')^2 

-1 

sage: ln(sefms('%e')) 

1 

sage: sefms('i')^2 

_i^2 

sage: sefms('I')^2 

_I^2 

sage: sefms('ln(e)') 

ln(_e) 

sage: sefms('%inf') 

+Infinity 

""" 

global _syms 

syms = symbol_table.get('maxima', {}).copy() 

 

if not len(x): 

raise RuntimeError("invalid symbolic expression -- ''") 

maxima.set('_tmp_', x) 

 

# This is inefficient since it so rarely is needed: 

#r = maxima._eval_line('listofvars(_tmp_);')[1:-1] 

 

s = maxima._eval_line('_tmp_;') 

 

formal_functions = maxima_tick.findall(s) 

if len(formal_functions): 

for X in formal_functions: 

try: 

syms[X[1:]] = _syms[X[1:]] 

except KeyError: 

syms[X[1:]] = function_factory(X[1:]) 

# You might think there is a potential very subtle bug if 'foo 

# is in a string literal -- but string literals should *never* 

# ever be part of a symbolic expression. 

s = s.replace("'","") 

 

delayed_functions = maxima_qp.findall(s) 

if len(delayed_functions): 

for X in delayed_functions: 

if X == '?%at': # we will replace Maxima's "at" with symbolic evaluation, not an SFunction 

pass 

else: 

syms[X[2:]] = function_factory(X[2:]) 

s = s.replace("?%", "") 

 

s = maxima_hyper.sub('hypergeometric', s) 

 

# Look up every variable in the symtable keys and fill a replacement list. 

cursor = 0 

l = [] 

for m in maxima_var.finditer(s): 

if m.group(0) in symtable: 

l.append(s[cursor:m.start()]) 

l.append(symtable.get(m.group(0))) 

cursor = m.end() 

if cursor > 0: 

l.append(s[cursor:]) 

s = "".join(l) 

 

s = s.replace("%","") 

 

s = s.replace("#","!=") # a lot of this code should be refactored somewhere... 

#we apply the square-bracket replacing patterns repeatedly 

#to ensure that nested brackets get handled (from inside to out) 

while True: 

olds = s 

s = polylog_ex.sub('polylog(\\1,', s) 

s = maxima_polygamma.sub('psi(\g<1>,', s) # this replaces psi[n](foo) with psi(n,foo), ensuring that derivatives of the digamma function are parsed properly below 

if s == olds: break 

 

if equals_sub: 

s = s.replace('=','==') 

# unfortunately, this will turn != into !==, which we correct 

s = s.replace("!==", "!=") 

 

#replace %union from to_poly_solve with a list 

if s[0:5]=='union': 

s = s[5:] 

s = s[s.find("(")+1:s.rfind(")")] 

s = "[" + s + "]" # turn it into a string that looks like a list 

 

#replace %solve from to_poly_solve with the expressions 

if s[0:5]=='solve': 

s = s[5:] 

s = s[s.find("(")+1:s.find("]")+1] 

 

#replace all instances of Maxima's scientific notation 

#with regular notation 

search = sci_not.search(s) 

while not search is None: 

(start, end) = search.span() 

r = create_RealNumber(s[start:end]).str(no_sci=2, truncate=True) 

s = s.replace(s[start:end], r) 

search = sci_not.search(s) 

 

# have to do this here, otherwise maxima_tick catches it 

syms['diff'] = dummy_diff 

syms['integrate'] = dummy_integrate 

syms['laplace'] = dummy_laplace 

syms['ilt'] = dummy_inverse_laplace 

syms['at'] = at 

 

global is_simplified 

try: 

# use a global flag so all expressions obtained via 

# evaluation of maxima code are assumed pre-simplified 

is_simplified = True 

_syms = symbol_table['functions'].copy() 

try: 

global _augmented_syms 

_augmented_syms = syms 

return SRM_parser.parse_sequence(s) 

finally: 

_augmented_syms = {} 

except SyntaxError: 

raise TypeError("unable to make sense of Maxima expression '%s' in Sage"%s) 

finally: 

is_simplified = False 

 

# Comma format options for Maxima 

def mapped_opts(v): 

""" 

Used internally when creating a string of options to pass to 

Maxima. 

 

INPUT: 

 

- ``v`` - an object 

 

OUTPUT: a string. 

 

The main use of this is to turn Python bools into lower case 

strings. 

 

EXAMPLES:: 

 

sage: sage.calculus.calculus.mapped_opts(True) 

'true' 

sage: sage.calculus.calculus.mapped_opts(False) 

'false' 

sage: sage.calculus.calculus.mapped_opts('bar') 

'bar' 

""" 

if isinstance(v, bool): 

return str(v).lower() 

return str(v) 

 

def maxima_options(**kwds): 

""" 

Used internally to create a string of options to pass to Maxima. 

 

EXAMPLES:: 

 

sage: sage.calculus.calculus.maxima_options(an_option=True, another=False, foo='bar') 

'an_option=true,foo=bar,another=false' 

""" 

return ','.join(['%s=%s'%(key,mapped_opts(val)) for key, val in six.iteritems(kwds)]) 

 

 

# Parser for symbolic ring elements 

 

# We keep two dictionaries syms_cur and syms_default to keep the current symbol 

# table and the state of the table at startup respectively. These are used by 

# the restore() function (see sage.misc.reset). 

# 

# The dictionary _syms is used as a lookup table for the system function 

# registry by _find_func() below. It gets updated by 

# symbolic_expression_from_string() before calling the parser. 

_syms = syms_cur = symbol_table.get('functions', {}) 

syms_default = dict(syms_cur) 

 

# This dictionary is used to pass a lookup table other than the system registry 

# to the parser. A global variable is necessary since the parser calls the 

# _find_var() and _find_func() functions below without extra arguments. 

_augmented_syms = {} 

 

 

def _find_var(name): 

""" 

Function to pass to Parser for constructing 

variables from strings. For internal use. 

 

EXAMPLES:: 

 

sage: y = var('y') 

sage: sage.calculus.calculus._find_var('y') 

y 

sage: sage.calculus.calculus._find_var('I') 

I 

""" 

try: 

res = _augmented_syms[name] 

except KeyError: 

pass 

else: 

# _augmented_syms might contain entries pointing to functions if 

# previous computations polluted the maxima workspace 

if not isinstance(res, Function): 

return res 

 

try: 

return SR.symbols[name] 

except KeyError: 

pass 

 

# try to find the name in the global namespace 

# needed for identifiers like 'e', etc. 

import sage.all 

try: 

return SR(sage.all.__dict__[name]) 

except (KeyError, TypeError): 

return var(name) 

 

def _find_func(name, create_when_missing = True): 

""" 

Function to pass to Parser for constructing 

functions from strings. For internal use. 

 

EXAMPLES:: 

 

sage: sage.calculus.calculus._find_func('limit') 

limit 

sage: sage.calculus.calculus._find_func('zeta_zeros') 

zeta_zeros 

sage: f(x)=sin(x) 

sage: sage.calculus.calculus._find_func('f') 

f 

sage: sage.calculus.calculus._find_func('g', create_when_missing=False) 

sage: s = sage.calculus.calculus._find_func('sin') 

sage: s(0) 

0 

""" 

try: 

func = _augmented_syms.get(name) 

if func is None: 

func = _syms[name] 

if not isinstance(func, Expression): 

return func 

except KeyError: 

pass 

import sage.all 

try: 

func = SR(sage.all.__dict__[name]) 

if not isinstance(func, Expression): 

return func 

except (KeyError, TypeError): 

if create_when_missing: 

return function_factory(name) 

else: 

return None 

 

SR_parser = Parser(make_int = lambda x: SR(Integer(x)), 

make_float = lambda x: SR(RealDoubleElement(x)), 

make_var = _find_var, 

make_function = _find_func) 

 

def symbolic_expression_from_string(s, syms=None, accept_sequence=False): 

""" 

Given a string, (attempt to) parse it and return the 

corresponding Sage symbolic expression. Normally used 

to return Maxima output to the user. 

 

INPUT: 

 

- ``s`` - a string 

 

- ``syms`` - (default: None) dictionary of 

strings to be regarded as symbols or functions 

 

- ``accept_sequence`` - (default: False) controls whether 

to allow a (possibly nested) set of lists and tuples 

as input 

 

EXAMPLES:: 

 

sage: y = var('y') 

sage: sage.calculus.calculus.symbolic_expression_from_string('[sin(0)*x^2,3*spam+e^pi]',syms={'spam':y},accept_sequence=True) 

[0, 3*y + e^pi] 

""" 

global _syms 

_syms = symbol_table['functions'].copy() 

parse_func = SR_parser.parse_sequence if accept_sequence else SR_parser.parse_expression 

if syms is None: 

return parse_func(s) 

else: 

try: 

global _augmented_syms 

_augmented_syms = syms 

return parse_func(s) 

finally: 

_augmented_syms = {} 

 

def _find_Mvar(name): 

""" 

Function to pass to Parser for constructing 

variables from strings. For internal use. 

 

EXAMPLES:: 

 

sage: y = var('y') 

sage: sage.calculus.calculus._find_var('y') 

y 

sage: sage.calculus.calculus._find_var('I') 

I 

""" 

if name[:10] == "_SAGE_VAR_": 

return var(name[10:]) 

res = _augmented_syms.get(name) 

if res is not None and not isinstance(res, Function): 

return res 

 

# try to find the name in the global namespace 

# needed for identifiers like 'e', etc. 

import sage.all 

try: 

return SR(sage.all.__dict__[name]) 

except (KeyError, TypeError): 

return var(name) 

 

SRM_parser = Parser(make_int = lambda x: SR(Integer(x)), 

make_float = lambda x: SR(RealDoubleElement(x)), 

make_var = _find_Mvar, 

make_function = _find_func)