程式碼與數學公式

Votes

Upvotes

0

Upvotes: 0

Downvotes

1

Downvotes: 1

Net votes

-1

Prompt

你隨便幫我寫一個有各種程式碼的訊息還有數學公式

Response

下面是一段「隨便寫的訊息」,裡面混合了各種程式碼片段 + 數學公式(Markdown/LaTeX 風格),你可以直接拿去測試貼到 README、論壇、Discord、Matrix、Notion 等格式渲染。

✅ 隨機混合訊息:程式碼 + 數學公式

我在整理一個小工具: 目標是從資料庫抓資料 → 做簡單分析 → 產生報表 → 丟到 API。

先定義幾個數學量:

  • 均方根誤差(RMSE): [ \mathrm{RMSE}=\sqrt{\frac{1}{N}\sum_{i=1}^{N}(y_i-\hat{y}_i)^2} ]

  • logistic 函數(常見於分類): [ \sigma(x)=\frac{1}{1+e^{-x}} ]

  • 梯度下降更新: [ \theta_{t+1}=\theta_t-\eta \nabla_{\theta}\mathcal{L}(\theta_t) ]

Python(資料處理 + 小分析)

from dataclasses import dataclass
import numpy as np
import pandas as pd

@dataclass
class Metrics:
    rmse: float
    mae: float

def compute_metrics(y_true, y_pred) -> Metrics:
    y_true = np.asarray(y_true, dtype=float)
    y_pred = np.asarray(y_pred, dtype=float)
    rmse = float(np.sqrt(np.mean((y_true - y_pred) ** 2)))
    mae  = float(np.mean(np.abs(y_true - y_pred)))
    return Metrics(rmse=rmse, mae=mae)

df = pd.DataFrame({
    "y": [1, 2, 3, 4],
    "yhat": [0.9, 2.2, 2.9, 4.1]
})
m = compute_metrics(df["y"], df["yhat"])
print(m)

Bash(抓 log + 一行管線)

#!/usr/bin/env bash
set -euo pipefail

LOG_DIR="/var/log/myapp"
grep -R "ERROR" "$LOG_DIR" \
  | awk -F':' '{print $1}' \
  | sort | uniq -c | sort -nr \
  | head -n 10

SQL(查詢 + 聚合)

-- 找出最近 7 天每位使用者的提問數
SELECT
  user_id,
  COUNT(*) AS question_count
FROM questions
WHERE created_at >= NOW() - INTERVAL '7 days'
GROUP BY user_id
ORDER BY question_count DESC
LIMIT 20;

JavaScript(呼叫 API + 重試)

async function fetchWithRetry(url, { retries = 3, backoffMs = 300 } = {}) {
  let lastErr;
  for (let i = 0; i < retries; i++) {
    try {
      const res = await fetch(url);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      return await res.json();
    } catch (e) {
      lastErr = e;
      await new Promise(r => setTimeout(r, backoffMs * (i + 1)));
    }
  }
  throw lastErr;
}

fetchWithRetry("https://example.com/api/status")
  .then(console.log)
  .catch(console.error);

YAML(設定檔)

app:
  name: "AskLog"
  env: "dev"
  features:
    verified: true
    rate_limit:
      enabled: true
      per_minute: 60

db:
  host: "localhost"
  port: 5432
  name: "asklog"
  user: "postgres"

Docker Compose(Postgres + App)

services:
  db:
    image: postgres:16
    environment:
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: asklog
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data

  app:
    build: .
    depends_on:
      - db
    environment:
      DATABASE_URL: "postgresql://postgres:postgres@db:5432/asklog"
    ports:
      - "8080:8080"

volumes:
  pgdata:

C++(小函式 + 範例)

#include <iostream>
#include <vector>
#include <numeric>

double mean(const std::vector<double>& x) {
  return std::accumulate(x.begin(), x.end(), 0.0) / x.size();
}

int main() {
  std::vector<double> x{1,2,3,4,5};
  std::cout << "mean=" << mean(x) << "\n";
}

Regex(快速過濾)

要抓像 Region_biastg_01d.csvRegion biastg 01d.csv

^(?<region>.+?)[ _](?<target>biastg|dbiastg)[ _](?<lead>\d{2})d\.csv$

如果你想要更「像真實專案」一點(比如:同時包含錯誤訊息 stack trace、log 範例、README 格式、公式推導),我也可以再幫你生成一段更長、更亂但更真實的版本。

Comments

Login to add a comment.

SneezyCat

[deleted]

Net votes 1 (↑1 / ↓0)
SneezyCat

[deleted]

Net votes 1 (↑1 / ↓0)
SneezyCat

[deleted]

Net votes 0 (↑0 / ↓0)
SneezyCat

[deleted]

Net votes 0 (↑0 / ↓0)
SneezyCat

[deleted]

Net votes 0 (↑0 / ↓0)