文章目录
- 对数计算尺 📏
- 示例代码
对数计算尺 📏
对数可以有效地把乘法转换成加法运算,比如:
l
n
A
∗
B
=
l
n
A
+
l
n
B
ln^{A*B} = ln^{A} + ln^{B}
lnA∗B=lnA+lnB
对数计算尺就是利用对数性质把乘法换成加法的一种辅助工具.
图片来自《程序员的数学1》
小玩意很有意思
示例代码
用Qt的视图框架写个demo
#include <QtWidgets>
QList<qreal> tickVals;
int times = 200;
class SimpleItem : public QGraphicsItem
{
public:
QRectF rect;
int moveSteps = 0;
QColor background;
SimpleItem():QGraphicsItem(),rect(0,0,600,30){
rect.setWidth(qLn(tickVals.size())*times+20);
qDebug() << tickVals ;
}
QRectF boundingRect() const override
{
return rect;
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
QWidget *widget) override
{
if(background.isValid())
painter->fillRect(rect,background);
painter->drawRect(rect);
for (int i = 0; i < tickVals.size(); ++i) {
auto tv = tickVals.at(i);
painter->drawLine(QLineF(tv,0,tv,rect.height()));
painter->drawText(tv,20,QString::number(i+1));
}
}
// QGraphicsItem interface
protected:
virtual void keyPressEvent(QKeyEvent *event) override {
switch (event->key()) {
case Qt::Key_Right:
moveSteps++;
moveSteps = moveSteps < tickVals.size() ? moveSteps : (tickVals.size()-1);
setPos(QPointF(tickVals.at(moveSteps),pos().y()));
break;
case Qt::Key_Left:
moveSteps--;
moveSteps = moveSteps < 0 ? 0 : moveSteps;
setPos(QPointF(tickVals.at(moveSteps),pos().y()));
break;
// case Qt::Key_Down:
// setPos(pos()+QPointF(0,rect.height()));
// break;
// case Qt::Key_Up:
// setPos(pos()+QPointF(0,-rect.height()));
// break;
default:
break;
}
}
};
int main(int argc, char** argv)
{
for (int i = 1; i <= 15; ++i) {
qreal t2 = qLn(i);
tickVals << (t2)*times;
}
QApplication a(argc,argv);
QGraphicsView view;
QGraphicsScene scene;
view.setScene(&scene);
auto si1 = new SimpleItem;
auto si2 = new SimpleItem;
si1->background = Qt::red;
si2->background = Qt::green;
si2->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsFocusable);
si1->moveBy(0,si1->rect.height());
scene.addItem(si1);
scene.addItem(si2);
si2->setSelected(true);
si2->setFocus();
view.scale(0.5,0.5);
// si2->grabKeyboard();
view.show();
a.exec();
return 0;
}