Circuit

2024-03-17
1 min read

C++

梯形电路稳态响应

以包含动态器件的 T 型电路为例(参考1第二章),使用 C++ 复数分析正弦稳态电路的代码如下(只支持 T 型电路)。下面代码在建立电路模型时,每个分支都使用 RLC 三元组进行描述

C++ 代码如下:

#include <complex>
#include <iostream>
#include <vector>

const double PI = 3.141592654;
using cnum_dbl = std::complex<double>;

struct BranchRLC {
  double R{}, L{}, C{};
};

struct LadderCkt {
  double freq{}; // Hz
  cnum_dbl power{};
  std::vector<BranchRLC> branchs_rlc{};

  std::vector<cnum_dbl> branch_v;
  std::vector<cnum_dbl> branch_i;
  std::vector<cnum_dbl> branch_z;
};

inline double calcu_w(double freq_hz) { return 2 * PI * freq_hz; }

cnum_dbl calcu_branch_z(BranchRLC rlc, double freq_hz) {
  const auto w = calcu_w(freq_hz);
  const double real = rlc.R;
  double img = rlc.L * w;
  if (rlc.C > 0.0) {
    img -= 1.0 / (rlc.C * w);
  }
  return cnum_dbl(real, img);
}

std::vector<cnum_dbl> calcu_branch_z(const LadderCkt &ckt) {
  std::vector<cnum_dbl> bz;
  bz.reserve(ckt.branchs_rlc.size());
  for (auto bi : ckt.branchs_rlc) {
    bz.push_back(calcu_branch_z(bi, ckt.freq));
  }

  return bz;
}

LadderCkt create_sample_ckt(int type = 0) {
  LadderCkt ckt;
  ckt.freq = 5000;
  ckt.power = cnum_dbl(1.0, 0.0);
  ckt.branchs_rlc = {{0, 0, 0}, {1, 0, 1}, {0, 0.5, 0}, {0, 0, 1}, {1, 0, 0}};
  return ckt;
}

void calcu_ckt_info(LadderCkt &ckt) {
  const auto branch_sz = ckt.branchs_rlc.size();
  ckt.branch_v.resize(branch_sz);
  ckt.branch_i.resize(branch_sz);
  ckt.branch_z = calcu_branch_z(ckt);

  const int n = branch_sz - 1;
  ckt.branch_v[n] = cnum_dbl(1.0, 0);
  ckt.branch_i[n] = ckt.branch_v[n] / ckt.branch_z[n];
  ckt.branch_i[n - 1] = ckt.branch_i[n];
  ckt.branch_v[n - 1] = ckt.branch_z[n - 1] * ckt.branch_i[n - 1];

  for (int k = n - 2; k >= 2; k = k - 2) {
    ckt.branch_v[k] = ckt.branch_v[k + 1] + ckt.branch_v[k + 2];
    ckt.branch_i[k] = ckt.branch_v[k] / ckt.branch_z[k];
    ckt.branch_i[k - 1] = ckt.branch_i[k] + ckt.branch_i[k + 1];
    ckt.branch_v[k - 1] = ckt.branch_z[k - 1] * ckt.branch_i[k - 1];
  }

  cnum_dbl ee = ckt.branch_v[1] + ckt.branch_v[2];
  cnum_dbl q = ckt.power / ee;
  for (int i = 1; i <= n; i++) {
    ckt.branch_i[i] *= q;
    ckt.branch_v[i] *= q;
  }
}

void print_ckt(const LadderCkt &ckt) {
  std::cout << "\nFreq(Hz): " << ckt.freq << std::endl;
  std::cout << "Power: " << ckt.power << std::endl;

  std::cout << "\nbranch i&u:" << std::endl;
  for (int i = 1; i < ckt.branchs_rlc.size(); i++) {
    std::cout << i << " " << ckt.branch_i[i] << " " << ckt.branch_v[i]
              << std::endl;
  }
}

int main() {
  auto sample_ckt = create_sample_ckt();
  calcu_ckt_info(sample_ckt);

  print_ckt(sample_ckt);
  return 0;
}

  1. 童梅, 孙士乾. 电路计算 C++ 与 MATLAB[M]. 清华大学出版社, 2007. ↩︎