存档:2009年三月

中国的数学家一代宗师–沈括

三月 30, 2009 | 数学 | RSS 2.0

近段时间一直看的好多数学都与西方有关,在数学百草园中看到一个祖国的一个一代宗师,沈括。
      沈括﹝公元1031-1095年﹞,字存中,杭州钱塘﹝今浙江杭州﹞人。据《宋史,沈括传》上的记载,沈括「博学善文,于天文、方志、律历、音乐、医药、卜算无所不通,皆有所论著。」晚年﹝公元1086-1095年﹞闲居润州﹝今江苏镇江﹞梦溪园潜心写作,成《梦溪笔谈》﹝约公元1088年﹞等有巨大科学价值的著作。  沈括对中国数学的卓越贡献主要是创立了「隙积术」﹝高阶等差级数的求和法﹞和「会圆术」﹝已知圆的直径和弓形的高,求弓形的弦和弧长的方法﹞。「隙积术」为数学研究开辟了一个新方向,从沈括开始,之后二、三百年间的杨辉、朱世杰等人关于「垛积问题」的研究,都受沈括的影响。他对「棋局都数」的研究则暗用了组合方法和指数定律
        说是这样一个故事,酒店里把就的坛子一层层地堆放的整整齐齐,成为一个梯形,最上层是4×8,第二层是5×9个,第三层是 6×10个,依次类推,没下去一层,长宽两边的坛子就增一个,共有七层,一个青年人进来,向酒坛里望了望,酒店师傅问它有多少个,青年脱口而出567个,算法是 中间一层7×11=77把这个数乘上7层数加上一个常数28.
公式(层数-1)x(层数)x(层数 +1)/12 这个就是隙积术 .高阶等差数列的求和法
 宋神宗元丰年间,沈括带兵反击西夏的侵扰时,详细的计算了人员,行程,日期,损耗等因素对粮食的需求关系,有效的解决了后勤,可见他对运筹学也是有一定造诣的

没有评论 »

周末相声俱乐部280期

三月 29, 2009 | 心情杂记 | RSS 2.0

昨天晚上去看了281期,虽然好多都已经看过,甚至看过三四次,但是非常经典。。。

没有评论 »

数据结构队列(七)memcache源码

三月 25, 2009 | c/c++, linux | RSS 2.0

队列(Queue)是一种数据结构,可以在队列的一端插入元素而在队列的另一端删除元素。

  ( 1 )允许删除的一端称为 队头( Front )
  ( 2 )允许插入的一端称为 队尾( Rear )
  ( 3 )当队列中没有元素时称为 空队列
  ( 4 )队列亦称作先进先出( First In First Out )的线性表,简称为 FIFO 表

队列的修改是依先进先出的原则进行的。新来的成员总是加入队尾(即不允许 ” 加塞 ” ),每次离开的成员总是队列头上的(不允许中途离队),即当前 ” 最老的 ” 成员离队。

多任务系统是一个典型的队列示例,在其中完成作业的调度。假设有五个程序等待执行, 它们将被放入一个队列,如果有第六个程序要执行,它将被放在队列的末尾。队列中首位的程序首先执行.程序代码

#include <stdio.h>
#define maxsize 10
typedef struct
{
    int elem[maxsize];
    int front,rear;
}queue;
void init_queue(queue *cp)
{
    cp->front=0;
    cp->rear=0;
}
void en_queue(queue *cp,int x)
{
    if((cp->rear+1)%maxsize==cp->front)
        printf(”The quequ is full!!”);
    else
    {
        cp->rear=(cp->rear+1)%maxsize;
        cp->elem[cp->rear]=x;
    }
}
int dl_queue(queue *cp)
{
    if(cp->front==cp->rear)
        printf(”The queue is empty!!”);
    else
    {
        cp->front=(cp->front+1)%maxsize;
        return(cp->elem[cp->front]);
     }
}
void print(queue *cp)
{
    int i;
    for(i=cp->front+1;i<=cp->rear;i++)
    {
        printf(”[%d]“,cp->elem[i]);
    }
}
void main()
{
    int x,y;
    int select;
    queue *cp=NULL;
    init_queue(cp);
    do
    {
        printf(”(1) Input a stack data”);
        printf(”(2) Output a stack data”);
        printf(”(3) Exit”);
        printf(”Please select one:”);
        scanf(”%d”,&select);
        switch(select)
        {
            case 1:printf(”Please input the data:”);
                   scanf(”%d”,&x);
                   en_queue(cp,x);
                   printf(”The queue is: “);
                   print(cp);
                   break;
            case 2:y=dl_queue(cp);
                   printf(”The queue is: “);
                   print(cp);
                   printf(”The putout data is %d”,y);
                   break;
            case 3:break;
        }
    }
    while(select<3);
    getch();
}

memcached :
#include “memcached.h”
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <errno.h>

#ifdef HAVE_MALLOC_H
#include <malloc.h>
#endif

#ifdef HAVE_STRING_H
#include <string.h>
#endif

#ifdef USE_THREADS

#include <pthread.h>

#define ITEMS_PER_ALLOC 64

/* An item in the connection queue. */
/*链接队列项 */
typedef struct conn_queue_item CQ_ITEM;
struct conn_queue_item {
    int     sfd;
    int     init_state;
    int     event_flags;
    int     read_buffer_size;
    int     is_udp;
    CQ_ITEM *next;
};

/*链接 队列*/
/* A connection queue. */
typedef struct conn_queue CQ;
struct conn_queue {
    CQ_ITEM *head;
    CQ_ITEM *tail;
    pthread_mutex_t lock;
    pthread_cond_t  cond;
};

/* Lock for connection freelist */
static pthread_mutex_t conn_lock;

/* Lock for alternative item suffix freelist */
static pthread_mutex_t suffix_lock;

/* Lock for cache operations (item_*, assoc_*) */
static pthread_mutex_t cache_lock;

/* Lock for slab allocator operations */
static pthread_mutex_t slabs_lock;

/* Lock for global stats */
static pthread_mutex_t stats_lock;

/*cq的连表*/
/* Free list of CQ_ITEM structs */
static CQ_ITEM *cqi_freelist;
static pthread_mutex_t cqi_freelist_lock;

/*
 * Each libevent instance has a wakeup pipe, which other threads
 * can use to signal that they’ve put a new connection on its queue.
 没一个 libevent实例都有一个别 的线程用信号唤醒的管道,他们最早队列中起个链接
 */
typedef struct {
    pthread_t thread_id;        /* unique ID of this thread 线程id*/
    struct event_base *base;    /* libevent handle this thread uses 线程用到的libeven的处理t */
    struct event notify_event;  /* listen event for notify pipe 监听事件来通知管道*/
    int notify_receive_fd;      /* receiving end of notify pipe 接受结束通知管道 */
    int notify_send_fd;         /* sending end of notify pipe 发送结束管道 */
    CQ  new_conn_queue;         /* queue of new connections to handle 新 的链接处理*/
} LIBEVENT_THREAD;

static LIBEVENT_THREAD *threads;

/*
 * Number of threads that have finished setting themselves up.
 */
static int init_count = 0;
static pthread_mutex_t init_lock;
static pthread_cond_t init_cond;

static void thread_libevent_process(int fd, short which, void *arg);

/*
 * Initializes a connection queue.
 */
static void cq_init(CQ *cq) {
    pthread_mutex_init(&cq->lock, NULL);
    pthread_cond_init(&cq->cond, NULL);
    cq->head = NULL;
    cq->tail = NULL;
}

/*
 * Waits for work on a connection queue.
 */
static CQ_ITEM *cq_pop(CQ *cq) {
    CQ_ITEM *item;

    pthread_mutex_lock(&cq->lock);
    while (NULL == cq->head)
        pthread_cond_wait(&cq->cond, &cq->lock);
    item = cq->head;
    cq->head = item->next;
    if (NULL == cq->head)
        cq->tail = NULL;
    pthread_mutex_unlock(&cq->lock);

    return item;
}

/*
 * Looks for an item on a connection queue, but doesn’t block if there isn’t
 * one.
 * Returns the item, or NULL if no item is available
 */
static CQ_ITEM *cq_peek(CQ *cq) {
    CQ_ITEM *item;

    pthread_mutex_lock(&cq->lock);
    item = cq->head;
    if (NULL != item) {
        cq->head = item->next;
        if (NULL == cq->head)
            cq->tail = NULL;
    }
    pthread_mutex_unlock(&cq->lock);

    return item;
}

/*
 * Adds an item to a connection queue.
 */
static void cq_push(CQ *cq, CQ_ITEM *item) {
    item->next = NULL;

    pthread_mutex_lock(&cq->lock);
    if (NULL == cq->tail)
        cq->head = item;
    else
        cq->tail->next = item;
    cq->tail = item;
    pthread_cond_signal(&cq->cond);
    pthread_mutex_unlock(&cq->lock);
}

/*
 * Returns a fresh connection queue item.
 */
static CQ_ITEM *cqi_new() {
    CQ_ITEM *item = NULL;
    pthread_mutex_lock(&cqi_freelist_lock);
    if (cqi_freelist) {
        item = cqi_freelist;
        cqi_freelist = item->next;
    }
    pthread_mutex_unlock(&cqi_freelist_lock);

    if (NULL == item) {
        int i;

        /* Allocate a bunch of items at once to reduce fragmentation */
        item = malloc(sizeof(CQ_ITEM) * ITEMS_PER_ALLOC);
        if (NULL == item)
            return NULL;

        /*
         * Link together all the new items except the first one
         * (which we’ll return to the caller) for placement on
         * the freelist.
         */
        for (i = 2; i < ITEMS_PER_ALLOC; i++)
            item[i - 1].next = &item[i];

        pthread_mutex_lock(&cqi_freelist_lock);
        item[ITEMS_PER_ALLOC - 1].next = cqi_freelist;
        cqi_freelist = &item[1];
        pthread_mutex_unlock(&cqi_freelist_lock);
    }

    return item;
}

/*
 * Frees a connection queue item (adds it to the freelist.)
 */
static void cqi_free(CQ_ITEM *item) {
    pthread_mutex_lock(&cqi_freelist_lock);
    item->next = cqi_freelist;
    cqi_freelist = item;
    pthread_mutex_unlock(&cqi_freelist_lock);
}

/*
 * Creates a worker thread.
 */
static void create_worker(void *(*func)(void *), void *arg) {
    pthread_t       thread;
    pthread_attr_t  attr;
    int             ret;

    pthread_attr_init(&attr);

    if ((ret = pthread_create(&thread, &attr, func, arg)) != 0) {
        fprintf(stderr, “Can’t create thread: %s”,
                strerror(ret));
        exit(1);
    }
}

/*
 * Pulls a conn structure from the freelist, if one is available.
 */
conn *mt_conn_from_freelist() {
    conn *c;

    pthread_mutex_lock(&conn_lock);
    c = do_conn_from_freelist();
    pthread_mutex_unlock(&conn_lock);

    return c;
}

/*
 * Adds a conn structure to the freelist.
 *
 * Returns 0 on success, 1 if the structure couldn’t be added.
 */
bool mt_conn_add_to_freelist(conn *c) {
    bool result;

    pthread_mutex_lock(&conn_lock);
    result = do_conn_add_to_freelist(c);
    pthread_mutex_unlock(&conn_lock);

    return result;
}

/*
 * Pulls a suffix buffer from the freelist, if one is available.
 */
char *mt_suffix_from_freelist() {
    char *s;

    pthread_mutex_lock(&suffix_lock);
    s = do_suffix_from_freelist();
    pthread_mutex_unlock(&suffix_lock);

    return s;
}

/*
 * Adds a suffix buffer to the freelist.
 *
 * Returns 0 on success, 1 if the buffer couldn’t be added.
 */
bool mt_suffix_add_to_freelist(char *s) {
    bool result;

    pthread_mutex_lock(&suffix_lock);
    result = do_suffix_add_to_freelist(s);
    pthread_mutex_unlock(&suffix_lock);

    return result;
}

/****************************** LIBEVENT THREADS *****************************/

/*
 * Set up a thread’s information.
 */
static void setup_thread(LIBEVENT_THREAD *me) {
    if (! me->base) {
        me->base = event_init();
        if (! me->base) {
            fprintf(stderr, “Can’t allocate event base”);
            exit(1);
        }
    }

    /* Listen for notifications from other threads */
    event_set(&me->notify_event, me->notify_receive_fd,
              EV_READ | EV_PERSIST, thread_libevent_process, me);
    event_base_set(me->base, &me->notify_event);

    if (event_add(&me->notify_event, 0) == -1) {
        fprintf(stderr, “Can’t monitor libevent notify pipe”);
        exit(1);
    }

    cq_init(&me->new_conn_queue);
}

/*
 * Worker thread: main event loop
 */
static void *worker_libevent(void *arg) {
    LIBEVENT_THREAD *me = arg;

    /* Any per-thread setup can happen here; thread_init() will block until
     * all threads have finished initializing.
     */

    pthread_mutex_lock(&init_lock);
    init_count++;
    pthread_cond_signal(&init_cond);
    pthread_mutex_unlock(&init_lock);

    return (void*) event_base_loop(me->base, 0);
}

/*
 * Processes an incoming “handle a new connection” item. This is called when
 * input arrives on the libevent wakeup pipe.
 */
static void thread_libevent_process(int fd, short which, void *arg) {
    LIBEVENT_THREAD *me = arg;
    CQ_ITEM *item;
    char buf[1];

    if (read(fd, buf, 1) != 1)
        if (settings.verbose > 0)
            fprintf(stderr, “Can’t read from libevent pipe”);

    item = cq_peek(&me->new_conn_queue);

    if (NULL != item) {
        conn *c = conn_new(item->sfd, item->init_state, item->event_flags,
                           item->read_buffer_size, item->is_udp, me->base);
        if (c == NULL) {
            if (item->is_udp) {
                fprintf(stderr, “Can’t listen for events on UDP socket”);
                exit(1);
            } else {
                if (settings.verbose > 0) {
                    fprintf(stderr, “Can’t listen for events on fd %d”,
                        item->sfd);
                }
                close(item->sfd);
            }
        }
        cqi_free(item);
    }
}

/* Which thread we assigned a connection to most recently. */
static int last_thread = -1;

/*
 * Dispatches a new connection to another thread. This is only ever called
 * from the main thread, either during initialization (for UDP) or because
 * of an incoming connection.
 */
void dispatch_conn_new(int sfd, int init_state, int event_flags,
                       int read_buffer_size, int is_udp) {
    CQ_ITEM …

没有评论 »

高效产生不重复的随机数

三月 24, 2009 | c/c++, 数学, 数据结构算法, 软件工程/编程技巧/设计模式 | RSS 2.0

编程珠玑里面的

for(i = 0; i < n; i++)
{
x[i] = i;
}
for(i = 0; i < k; i++)
{
t = rand(i,n-1);
swap(x[i], x[t]);
out(x[i]);
}

没有评论 »

周末相声俱乐部-为刘颖喝彩

三月 22, 2009 | 心情杂记 | RSS 2.0

今天是21号,周六习惯性的从周末相声俱乐部回来,想过好几次了,一直没写,记得是年轻大概11月份我开始去东图去看相声,主要是干开始不知道,首先我知道了哪里可以免费借书看,公共图书馆,发现了这里,真像是像哥伦布发现了新大陆,以后我基本上每周都从哪里借了好多书看,从刚开始的拿破仑,等,艺术,武侠,哲学等都有涉猎,特别是专业课,发现看的最多的居然是与数学相关的,从干开始看数论妙趣,到现在一发不可收拾,那几架关于数理的,起码我题目大部分都看过,也浏览了基本经典的,扯远了,现在说说相声。
   上周去的时候,前两排的中间被两道栏给软禁了,猜到了可能是领导来,后来发生了一件小事,可能是有个现场的管理员估计是领导多,想让右排的有个老先生让位,可能没沟通好,两位闹起来了。老大爷也是急啊。呵呵。等相声一开始刘颖的圆场真是爽快,一上台,就连鞠三次躬,说第一位鞠躬给哪位老先生,说对不住了。。。。第二位给现场管理员,最后给观众,最后把责任全给揽过来了,说这个都是我们说相声的不对等,挺开阔的胸襟,不管是真是假,但真是个大老爷们,敢于承担责任。第一次见他说相声是和李金斗,张浩楠,三个一起说的教你模仿,他们两个是李金斗的徒弟,演的很好,特别是模仿很像。上次说的也很好,在网上看了几段他说的段子,确实不错。学习下。

没有评论 »

数据结构系列循环队列(六 )

三月 20, 2009 | c/c++, 数据结构算法 | RSS 2.0

引用:http://learn.akae.cn/media/ch12s05.html
我们介绍一种新的数据结构--环形队列(Circular Queue)。把queue数组想像成一个圈,head和tail指针仍然是一直增大的,当指到数组末尾时就自动回到数组开头,就像两个人围着操场赛跑,沿着它们跑的方向看,从head到tail之间是队列的有效元素,从tail到head之间是空的存储位置,head追上tail就表示队列空了,tail追上head就表示队列的存储空间满了。如下图所示
数据结构系列循环队列(六 ) - 玉树临风 - 小和尚真情无限

#define MAXQSIZE 100

typedef struct {
    int *base;//循环队列的存储空间
    int front ;
    int rear;
}SqQueue;
/*初始化*/
int InitQueue(SqQueue  *Q) {
    Q->base = (int *)malloc(MAXQSIZE*sizeof(int));
    if(!Q->base) return -1;

    Q->front = 0;
    Q->rear = 0;
    return 0;
}
/*元素e加入队,成功为0 ,否则返回1*/
int EnQueue(SqQueue *Q,int e) {
    if((Q->rear+1)%MAXQSIZE == Q->font) return -1;
    Q->base[Q->rear] = e;
    Q->rear = (Q->rear +1)%MAXQSIZE;
}
/*出队列*/
int DeQueue(SqQueue *Q,int *c) {
    if(Q->rear == Q->front) return -1;
    *e = Q->base[Q->front];
    Q->front = (Q->front+1)%MAXQSIZE;
    return 0;

}

没有评论 »

数据结构系列栈解决迷宫问题(五)

三月 18, 2009 | c/c++, 数据结构算法 | RSS 2.0

文本中的信息
8 8 //行数列数
1 1 8 8//入口,出口
0 0 1 0 0 0 1 0
0 0 1 0 0 0 1 0
0 0 0 0 1 1 0 0
0 1 1 1 0 0 0 0
0 0 0 1 0 0 0 0
0 1 0 0 0 1 0 0
0 1 1 1 0 1 1 0
1 0 0 0 0 0 0 0
/*
@author : jk
@datetime:2009-3-18 0:55
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAXSIZE 50
#define ERROR -1
#define OK 0
#define FALSE 0
#define TRUE 1

typedef enum{RIGHT,DOWN,LEFT,UP} Direction;
typedef enum{YES,NO} MarkTag;
typedef struct position {
    int x;int y;
}Position;/*坐标*/

typedef struct {
 int order ;/*当前位置在路径中的序号*/
 Position seat;/* 当前位置在迷宫中的坐标*/
 Direction di; /*当前位置走到下一个位置的放方向*/
}SElemType;/*栈元素的类型*/

typedef struct {
    SElemType *elem;
    int top;
}Stack;
char maze[MAXSIZE+2][MAXSIZE+2];/*二维字符串数组表示迷宫*/
/*初始化一个栈*/
int InitStack(Stack *S) {
    /*创建一个空栈*/
  S->elem = (SElemType *)malloc(MAXSIZE*MAXSIZE*sizeof(SElemType));
  if(!S->elem) return ERROR;
  S->top = 0 ;
  return OK;
}
/*入栈*/
int Push(Stack *S,SElemType e) {/*元素e如栈*/
    if(S->top >= MAXSIZE*MAXSIZE)return ERROR;
    S->elem[S->top++] = e;
    return OK;
}
/*出栈*/
int Pop(Stack *S,SElemType e)  {/*栈顶出栈,由e带回栈顶元素*/
    if(S->top <= 0) return ERROR;
    *e = S->elem[S->top--] = e;
    return OK;
}
/*判定为空*/
int Empty(Stack S) {/*若栈为空,函数返回TRUE ,否则FALSE*/
  if(S.top == 0) return TRUE;
  return OK;
}
/*创建迷宫*/
int createMaze(char *filename,Position *startpos,Position *endpos) {
    /*从文件中读出迷宫所需要的信息*/
      FILE *fp;
    int i,j,rows,cols,temp;
    Position start,end;
    fp = fopen(filename,”r”);
    if(!fp) {
        printf(”open file %s error!”,filename);
        return ERROR;
    }
    if(!feof(fp)) {
        fscanf(fp,”%d%d”,&rows,&cols);/*读入迷宫的行数和列数*/
        fscanf(fp,”%d%d”,&start,x,&start.y);/*读入迷宫的入口位置 */
        fscanf(fp,”%d%d”,&end,x,&end.y);/*读入迷宫的出口位置 */
    }

    for(i = 1; i <= rows, i++) {
        for(j = 1 ; i <= cols;j++) {
            fscanf(fp,”%d”,&temp);
            maze[i][j] = 48 +temp;
        }
    }
    fclose(fp);
    /*在四周加墙壁*/
    for(i = 0,j = 0;i <= rows+1;i++) maze[i][j] = ‘1′;
    for(i = 0,j = cols+1;i <= rows+1;i++) maze[i][j] = ‘1′;
    for(i = 0,j = 0;j <= cols+1;j++) maze[i][j] = ‘1′;
    for(i = rows+1,j = 0;j <= cols+1;j++) maze[i][j] = ‘1′;
    return OK;
}
int canPass(Position curpos) {
    if(maze[curpos.x][curpos.y] == ‘0′) return TRUE;
    return FALSE;
}
void markPos(Position curpos,MarkTag tag) {/*为已经搜索过的位置添加标记*/

  switch(tag) {

      case YES: maze[curpos.x][curpos.y] = ‘.’;break;/*路径标记*/

      case NO: maze[curpos.x][curpos.y] = ‘#’;break;/*死胡同`标记*/
  }
}
Position nextPos(Position curpos,Direction dir) {
    Position nextpos;
    switch(dir) {
        case RIGHT : nextpos.x = curpos.x;nextpos.y = curpos.y+1;break;
        case DOWN : nextpos.x = curpos.x +1 ;nextpos.y = curpos.y;break;
        case LEFT : nextpos.x = curpos.x;nextpos.y = curpos.y-1;break;
        case UP : nextpos.x = curpos.x-1;nextpos.y = curpos.y;break;
    }

}
Direction nextDir(Direction dir) {
    switch(dir) {
      case RIGHT :return DOWN;
      case DOWN : return LEFT;
      case LEFT :UP;
    }

}
int Solve(Stack *S,Position start,Position end) {
    /*若迷宫中存在从入口start到出口end的通道则求出一条放在栈中,并返回true*/
    /*若迷宫中不存在从入口start到出口end的通道则求出一条放在栈中,并返回fale*/
      Position curpos;
    SElemType e;
    int curstep = 1;
    if(InitStack(S) == ERROR) return FALSE;
    curpos = start;
    do{
        if(canPass(curpos)) { /*this postion can pass*/
            markPos(curpos,YES);
            e.order = curstep;
            e.seat = curpos;
            e.di = RIGHT;
            Push(S.e);/*当前位置加入路径*/
            if(curpos.x == end.x && curpos.y == end.y) /*出口*/
              return TRUE;
            curpos = nextPos(curpos,RIGHT);   
            curstep++;
       
        }else {/*can’t pass this postion*/
          if(!Empty(*S)) {
              if(Pop(S,&e) == ERROR) return FALSE;
            while(e.di == UP && !Empty(*S)) {
                /*四个方向都探索过没有路,不能继续探索,回溯*/
                curpos = e.seat;makPos(curpos,NO);
                if(POP(S,&e) == ERROR) return FALSE;
           
            }
         
            if(e.di != UP)  {/*四个方向探索*/
                  e.di = nextDir(e.di);
                Push(S,e);
                curpos = nextPos(e.seat,e.di);
            }
          }
       
       
        }
   
    }while(!Empty(*S));
    return FALSE;
}
int main() {
      Position startPos,endPos;
    Stack path;
    SElemType e;
    char *fname=”in.txt”;   
    if{createMaze(fname,&startPos,&endPos) == ERROR} return EXIT_FAILURE;
    Solve(&path ,startPos,endPos);
    while(!Empty(path)) {/*输出入口路径*/
        Pop(&path,&e)
        printf(”(%d,%d)”,e.seat.x,e.seat.y);
   
    }

}

没有评论 »

数学的奇妙

三月 17, 2009 | 数学 | RSS 2.0

1数学中的逼近思想:
在古希腊的时候人们已经用梯子的逼近思想去算根号2的值
1 1
2 3
5 8
13 21
等等,思想是把上一个梯子的总数相加得到左边的,然后右边的是左边的加上上一个梯子右边的。
2/3,5/8,13/21,。。。。。。一步步逼近根号2.
还有许多这方面的,特别是对派的计算的逼近思想,如正n变形无限大时就逼近园来算派的比率,还有通过随机概率算法来逼近的,如著名的蒙特卡落算法,抛针算法求派。等
2 数学中的黄金分割点
数学中的黄金分割点名不虚传,有一幅名画中,才看的在《数学的奇妙》这本书里面讲的竟然有十三处都用了黄金分割点,包括达芬奇的画也有,达芬奇的众多画都用了数学中的好多知识,透视,摄影几何等。而且达芬奇发现了好多奇妙的比例。忘记了。黄金分割点永远是我们看着最舒服的点,而且奇怪的是菲薄纳妾数列的两项比值也和黄金分割点相关。

没有评论 »

数据结构系列栈后缀表达式(四)

三月 10, 2009 | c/c++, 数据结构算法 | RSS 2.0

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define add 43
#define subs 45
#define mult 42
#define div 47
#define MAXSIZE 100
typedef struct {
    int stkdata[MAXSIZE];
    int top ;
}STKzone;

typedef STKzone *STK;
typedef enum{true=1,false=0} bool;
typedef enum{ok,error} status;
STKzone expSTKzone;
STK expSTK;

/*执行栈的初始化,建栈指针*/
STK initSTK(STKzone *stack_zone) {
      STK p;
    p = stack_zone;
    p->top=0;
}
/*将一些结构型数据送入栈中*/
status push(int *term,STK pstk) {
    if(pstk->top == MAXSIZE)  {
        return error;
    }
    pstk->stkdata[pstk->top] = *term;
    (pstk->top)++;/*栈顶指针移动 */
    return ok;

}
/*判定栈是否为空*/
bool emptySTK(STK pstk) {

    return (pstk->top == 0);    
}
/*从栈内出来一些数据结构 */
status pop(int *pdata, STK pstk) {

  if(emptySTK(pstk))
    return error;
  (pstk->top)–;
  *pdata = pstk->stkdata[pstk->top];
  return ok;
}
void synerror(void) {
    printf(”表达式语法错误”);
    exit(1);
}
int eval (char tag,int a1,int a2) {

    switch(tag) {
        case add:return (a1+a2);
        case subs:return (a1-a2);
        case mult: return (a1*a2);

        case div: return (a1/a2);
    
    }

}
int main() {
    char c;
    int opd1,opd2,temp,c1;
    expSTK = initSTK(&expSTKzone);

    printf(”后置表达式”);
    while((c=getchar())!= ”) {
    
      if(c==’ ‘) continue ;
      if((c>47)&&(c<58)) {
      
          putchar(c);
        c1=c-48;
        if(push(&c1,expSTK)==error){/*运算夫进栈*/
           printf(”表达式太长”);
          exit(0);
        }
      
      }else if((c == add) || (c == subs) || (c==mult)||(c==div)){
          putchar(c);
        if(pop(&opd1,expSTK) == error) synerror();
        if(pop(&opd2,expSTK) == error) synerror();
        temp = eval(c,opd2,opd1);
        push(&temp,expSTK);
      
      }else synerror();
    
    }
    if((pop(&opd1,expSTK)==error)) synerror();
    if(!(emptySTK(expSTK))) synerror();
    printf(”=%-3d”,opd1);

}

没有评论 »

ubuntu下用c操作mysql

三月 10, 2009 | c/c++, linux | RSS 2.0

首先需要安装apt-get install mysql-server-5.0 php5-mysq
然后查看
sudo netstat -tap | grep mysql
或者ps aux|grep mysql
确定启动后

sudo apt-get install libmysqlclient15-dev

#include  <stdlib.h>
#include  <stdio.h>
#include “/usr/include/mysql/mysql.h”
int main(int argc, char *argv[])
{
    MYSQL *conn_ptr;
    conn_ptr = mysql_init(NULL);
    if(!conn_ptr) {
        fprintf(stderr,”mysql_init failed “);
        return EXIT_FAILURE;
    }
    conn_ptr  = mysql_real_connect(conn_ptr,”localhost”,”root”,”123456″,”mysql”,0,NULL,0);
    if(conn_ptr) {
        printf(”connetion success”);
    }else {
        printf(”connetion failed”);
    }

    mysql_close(conn_ptr);
    return EXIT_SUCCESS;
}
$: gcc -I/usr/include/mysql connection.c  -L/usr/lib/mysql -lmysqlclient -lz -o connection
gcc -I/usr/include/mysql connection.c  -lmysqlclient -o connection 都可以进行链接

#include <stdio.h>
#include <stdlib.h>
#include “mysql.h”
/*注意哦,上面也可以是mysql.h的绝对地址,一般在mysql下的include目录下,仔细看看你的在哪里?*/

int main(int argc, char *argv[])
{
  MYSQL my_connection;

  int res;

  mysql_init(&my_connection);

  /*mysql_real_connect(&mysql,host,user,passwd,dbname,0,NULL,0)
   * == NULL)*/
  if (mysql_real_connect(&my_connection, “localhost”, “root”, “123456″,”cusemysql”,0,NULL,CLIENT_FOUND_ROWS))
  {
    printf(”Connection success”);
    res = mysql_query(&my_connection, “insert into children values(11,’Anny’,5)”);

    if (!res)
    {  
      printf(”Inserted %lu rows”,(unsigned long)mysql_affected_rows(&my_connection));
      /*里头的函数返回受表中影响的行数*/
    }
    else
    {
      //分别打印出错误代码及详细信息
      fprintf(stderr, “Insert error %d: %s”,mysql_errno(&my_connection),mysql_error(&my_connection));
    }
    mysql_close(&my_connection);
  }

  else
  {
    fprintf(stderr, “Connection failed”);

    if (mysql_errno(&my_connection))
    {
      fprintf(stderr, “Connection error %d: %s”,mysql_errno(&my_connection),mysql_error(&my_connection));
    }
  }
  return EXIT_SUCCESS;
}

没有评论 »