🛰️航天仿真算法库 SpaceAST 0.0.1
载入中...
搜索中...
未找到
Polynomial.hpp
浏览该文件的文档.
1
20
21#pragma once
22
23#include "AstGlobal.h"
24#include "AstUtil/StringView.hpp"
25#include <vector>
26#include <string>
27
28AST_NAMESPACE_BEGIN
29
36class Polynomial;
37
43AST_UTIL_API errc_t aParsePolynomial(StringView content, StringView varname, std::vector<double>& coeffs);
44
45
50AST_UTIL_API errc_t aParsePolynomial(StringView content, std::vector<double>& coeffs);
51
52
57AST_UTIL_API std::string aFormatPolynomial(const std::vector<double>& coeffs, StringView varname);
58
59
62{
63public:
64 Polynomial() = default;
65 Polynomial(const std::initializer_list<double>& init)
66 : coeffs_{init}
67 {}
68 Polynomial(const std::vector<double>& coeff)
69 : coeffs_{coeff}
70 {}
71 ~Polynomial() = default;
72
77 errc_t parse(StringView content, StringView varname){
78 return aParsePolynomial(content, varname, coeffs_);
79 }
80
84 errc_t parse(StringView content){
85 return aParsePolynomial(content, coeffs_);
86 }
87
91 std::string toString(StringView varname)
92 {
93 return aFormatPolynomial(coeffs_, varname);
94 }
95
96 const std::vector<double>& coeffs() const { return coeffs_; }
97 std::vector<double>& coeffs() { return coeffs_; }
98 void setCoeffs(const std::vector<double>& coeffs){ coeffs_ = coeffs; }
99 void setCoeffs(std::vector<double>&& coeffs){ coeffs_ = std::move(coeffs); }
100
104 double eval(double x) const;
105protected:
106 std::vector<double> coeffs_;
107};
108
109
110// Horner法则/秦九韶算法计算多项式值
111inline double Polynomial::eval(double x) const
112{
113 if(coeffs_.size() == 0){
114 return 0;
115 }
116 else if(coeffs_.size() == 1)
117 {
118 return coeffs_[0];
119 }
120 else{
121 // 使用 Horner 法则计算多项式值
122 double temp = coeffs_.back();
123 for (int i = (int)coeffs_.size() - 2; i >= 0; --i) {
124 temp *= x;
125 temp += coeffs_[i];
126 }
127 return temp;
128 }
129}
130
131A_ALWAYS_INLINE errc_t aParsePolynomial(StringView content, Polynomial& poly)
132{
133 return poly.parse(content);
134}
135
136A_ALWAYS_INLINE errc_t aParsePolynomial(StringView content, StringView varname, Polynomial& poly)
137{
138 return poly.parse(content, varname);
139}
140
144AST_NAMESPACE_END
多项式类
定义 Polynomial.hpp:62
std::string toString(StringView varname)
将多项式表达式转换为字符串
定义 Polynomial.hpp:91
errc_t parse(StringView content, StringView varname)
解析多项式表达式
定义 Polynomial.hpp:77
errc_t parse(StringView content)
解析多项式表达式(默认变量名 "x")
定义 Polynomial.hpp:84
std::string aFormatPolynomial(const std::vector< double > &coeffs, StringView varname)
将系数向量格式化为多项式表达式字符串
定义 Polynomial.cpp:180
errc_t aParsePolynomial(StringView content, StringView varname, std::vector< double > &coeffsOut)
解析多项式表达式
定义 Polynomial.cpp:30