第三章练习题答案

  • 3.1 修改无限制的float64值,跳过无效的多边形
  • 3.2 试验math包中其他函数的渲染图形 马鞍面
  • 3.3根据高度给每个多边形上色
  • 3.4 构造web服务器,返回SVG数据给客户端
  • 3.5 实现一个彩色的Mandelbrot图像
  • 3.6 实现升采样技术
  • 3.7 使用牛顿法来求解一个复数方程(z4−1=0z^4-1=0z4−1=0)生成分形图像
  • 3.8 通过提高精度来生成更多级别的分形
  • 3.9 web服务器,用于给客户端生成分形的图像
  • 3.10 非递归版本的comma函数,使用bytes.Buffer
  • 3.11 支持浮点数处理和一个可选的正负号的处理
  • 3.12 判断两个字符串是否是是相互打乱的
  • 3.13 编写KB、MB的常量声明

3.1 修改无限制的float64值,跳过无效的多边形

// 只需修改f函数
func f(x, y float64) float64 {r := math.Hypot(x, y) // distance from (0,0)if math.IsInf(r, 0) || math.IsNaN(r) {return 0}return math.Sin(r) / r
}

3.2 试验math包中其他函数的渲染图形 马鞍面

// 只需替换f函数
func corner(i, j int) (float64, float64) {// Find point (x,y) at corner of cell (i,j).x := xyrange * (float64(i)/cells - 0.5)y := xyrange * (float64(j)/cells - 0.5)// Compute surface height z.z := f_saddle(x, y)// Project (x,y,z) isometrically onto 2-D SVG canvas (sx,sy).sx := width/2 + (x-y)*cos30*xyscalesy := height/2 + (x+y)*sin30*xyscale - z*zscalereturn sx, sy
}func f_saddle(x, y float64) float64 {return x*x/600 - y*y/600
}

3.3根据高度给每个多边形上色

颜色确实是画出来了,就是真的好丑hhhh

func corner(i, j int) (float64, float64, float64) {// Find point (x,y) at corner of cell (i,j).x := xyrange * (float64(i)/cells - 0.5)y := xyrange * (float64(j)/cells - 0.5)// Compute surface height z.z := f(x, y)         //保存高度用于设置颜色// Project (x,y,z) isometrically onto 2-D SVG canvas (sx,sy).sx := width/2 + (x-y)*cos30*xyscalesy := height/2 + (x+y)*sin30*xyscale - z*zscalereturn sx, sy, z
}
func f(x, y float64) float64 {r := math.Hypot(x, y) // distance from (0,0)if math.IsInf(r, 0) || math.IsNaN(r) {return 0}return math.Sin(r) / r
}func f_saddle(x, y float64) float64 {return x*x/600 - y*y/600
}func test_3_3() {f, err := os.OpenFile("./pic.svg", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)if err != nil {fmt.Println("file open failed: ", err)}defer f.Close()fmt.Fprintf(f, "<svg xmlns='http://www.w3.org/2000/svg' "+"style='stroke: grey; fill: white; stroke-width: 0.7' "+"width='%d' height='%d'>", width, height)for i := 0; i < cells; i++ {for j := 0; j < cells; j++ {ax, ay, az := corner(i+1, j)bx, by, bz := corner(i, j)cx, cy, cz := corner(i, j+1)dx, dy, dz := corner(i+1, j+1)height := (az + bz + cz + dz) / 4     // 取四个顶点的高度平均值red, blue := 0, 0if height > 0 {red = int(height * 256)  // 如果高度为正则显示红色,否则显示蓝色} else {blue = int(-height * 256)}fmt.Fprintf(f, "<polygon points='%g,%g %g,%g %g,%g %g,%g' style=\"fill: #%02x00%02x;\"/>\n",ax, ay, bx, by, cx, cy, dx, dy, red, blue)}}fmt.Fprintln(f, "</svg>")
}

3.4 构造web服务器,返回SVG数据给客户端

var (width, height = 600, 320                     // canvas size in pixelscells         = 100                          // number of grid cellsxyrange       = 30.0                         // axis ranges (-xyrange..+xyrange)xyscale       = float64(width) / 2 / xyrange // pixels per x or y unitzscale        = float64(height) * 0.4        // pixels per z unitangle         = math.Pi / 6                  // angle of x, y axes (=30°)color         = "000000"                     //color of picture
)var sin30, cos30 = math.Sin(angle), math.Cos(angle) // sin(30°), cos(30°)func corner(i, j int) (float64, float64) {// Find point (x,y) at corner of cell (i,j).x := xyrange * (float64(i)/float64(cells) - 0.5)y := xyrange * (float64(j)/float64(cells) - 0.5)// Compute surface height z.z := f(x, y)// Project (x,y,z) isometrically onto 2-D SVG canvas (sx,sy).sx := float64(width)/2 + (x-y)*cos30*xyscalesy := float64(height)/2 + (x+y)*sin30*xyscale - z*zscalereturn sx, sy
}func f(x, y float64) float64 {r := math.Hypot(x, y) // distance from (0,0)if math.IsInf(r, 0) || math.IsNaN(r) {return 0}return math.Sin(r) / r
}func test_3_4(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "image/svg+xml")err := r.ParseForm()if err != nil {fmt.Fprintln(w, "request parse error: ", err)}// 判断query参数是否有效,无效则使用默认值if w := r.Form.Get("width"); w != "" {width, _ = strconv.Atoi(w)}if h := r.Form.Get("height"); h != "" {height, _ = strconv.Atoi(h)}if c := r.Form.Get("color"); c != "" {color = r.Form.Get("color")}fmt.Fprintf(w, "<svg xmlns='http://www.w3.org/2000/svg' "+"style='stroke: grey; fill: white; stroke-width: 0.7' "+"width='%d' height='%d'>", width, height)for i := 0; i < cells; i++ {for j := 0; j < cells; j++ {ax, ay := corner(i+1, j)bx, by := corner(i, j)cx, cy := corner(i, j+1)dx, dy := corner(i+1, j+1)fmt.Fprintf(w, "<polygon points='%g,%g %g,%g %g,%g %g,%g' style=\"fill: #%s;\"/>\n",ax, ay, bx, by, cx, cy, dx, dy, color)}}fmt.Fprintln(w, "</svg>")
}func main() {http.HandleFunc("/", test_3_4)err := http.ListenAndServe(":9999", nil)if err != nil {fmt.Println("server listen error: ", err)}
}

3.5 实现一个彩色的Mandelbrot图像

// 只需修改mandelbrot函数
func mandelbrot(z complex128) color.Color {const iterations = 200const contrast = 15var v complex128for n := uint8(0); n < iterations; n++ {v = v*v + zif cmplx.Abs(v) > 2 {// return color.Gray{255 - contrast*n}return color.RGBA{255, 125, 1, 255 - contrast*n}}}return color.Black
}

3.6 实现升采样技术

不确定理解的对不对,但这不是将width, height都扩大两倍就可以实现的吗?

 const (xmin, ymin, xmax, ymax = -2, -2, +2, +2width, height          = 2048, 2048)

3.7 使用牛顿法来求解一个复数方程(z4−1=0z^4-1=0z4−1=0)生成分形图像

// 用于求解的方称
func f(x complex128) complex128 {return x*x*x*x - 1
}// 该方程的导数
func fd(x complex128) complex128 {return 4 * x * x * x
}// 使用牛顿法求解方程f
func someEquation(z complex128) color.Color {var times uint8 = 0for (cmplx.Abs(f(z)) > 0.0001) && (times < 255) { //当f(z)约等于0或循环次数超过255时结束循环times++z = z - f(z)/fd(z) //牛顿法求解}return color.Gray{255 - times}
}func main() {const (xmin, ymin, xmax, ymax = -2, -2, +2, +2width, height          = 1024, 1024)img := image.NewRGBA(image.Rect(0, 0, width, height))for py := 0; py < height; py++ {y := float64(py)/height*(ymax-ymin) + yminfor px := 0; px < width; px++ {x := float64(px)/width*(xmax-xmin) + xminz := complex(x, y)// Image point (px, py) represents complex value z.// img.Set(px, py, mandelbrot(z))img.Set(px, py, someEquation(z))}}f, err := os.OpenFile("./someEquation.png", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)if err != nil {fmt.Println("file open failed,err:", err)}defer f.Close()png.Encode(f, img) // NOTE: ignoring errors
}

3.8 通过提高精度来生成更多级别的分形

func mandelbrot(z complex64) color.Color {const iterations = 200const contrast = 15var v complex64for n := uint8(0); n < iterations; n++ {v = v*v + zif real(v)*real(v)+imag(v)*imag(v) > 2 {// return color.Gray{255 - contrast*n}return color.RGBA{255, 125, 1, 255 - contrast*n}}}return color.Black
}
func main() {const (xmin, ymin, xmax, ymax = -2, -2, +2, +2width, height          = 1024, 1024)img := image.NewRGBA(image.Rect(0, 0, width, height))for py := 0; py < height; py++ {y := float32(py)/height*(ymax-ymin) + yminfor px := 0; px < width; px++ {x := float32(px)/width*(xmax-xmin) + xminz := complex(x, y)// Image point (px, py) represents complex value z.img.Set(px, py, mandelbrot(z))}}f, err := os.OpenFile("./image/mandelbrot_complex64.png", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)if err != nil {fmt.Println("file open failed,err:", err)}defer f.Close()png.Encode(f, img) // NOTE: ignoring errors
}

3.9 web服务器,用于给客户端生成分形的图像

不确定这个zoom参数的意思是否理解正确,有问题欢迎指正

func Fractal(f io.Writer, width int, height int) {const (xmin, ymin, xmax, ymax = -2, -2, +2, +2// width, height          = 1024, 1024)img := image.NewRGBA(image.Rect(0, 0, width, height))for py := 0; py < height; py++ {y := float64(py)/float64(height)*(ymax-ymin) + yminfor px := 0; px < width; px++ {x := float64(px)/float64(width)*(xmax-xmin) + xminz := complex(x, y)// Image point (px, py) represents complex value z.img.Set(px, py, mandelbrot(z))}}png.Encode(f, img) // NOTE: ignoring errors
}func test_3_9(w http.ResponseWriter, r *http.Request) {// 从HTTP参数中获取长、宽、放大倍数r.ParseForm()width, height, zoom := 1024, 1024, 1if s := r.Form.Get("x"); s != "" {width, _ = strconv.Atoi(s)}if s := r.Form.Get("y"); s != "" {height, _ = strconv.Atoi(s)}if s := r.Form.Get("zoom"); s != "" {zoom, _ = strconv.Atoi(s)}Fractal(w, width*zoom, height*zoom)
}// web服务器,用于给客户端生成分形的图像
func main() {http.HandleFunc("/", test_3_9)if err := http.ListenAndServe(":9999", nil); err != nil {fmt.Println("server listen error,err:", err)}
}

3.10 非递归版本的comma函数,使用bytes.Buffer

// 非递归版本的comma函数,使用bytes.Buffer
func test_3_10(s string) {len := len(s)var buf bytes.Bufferfor i := 0; i < len%3; i++ {buf.WriteByte(s[i])}if len%3 != 0 {buf.WriteByte(',')}for i := len % 3; i < len; {buf.WriteString(s[i : i+3])i += 3if i != len { // 不是最后一组均写入','buf.WriteByte(',')}}fmt.Println(buf.String())
}func main() {var num stringfmt.Print("please input a number:")_, _ = fmt.Scanln(&num)test_3_10(num)
}

3.11 支持浮点数处理和一个可选的正负号的处理

// 非递归版本的comma函数,使用bytes.Buffer,支持可选的+,-号
func test_3_10(s string) string {len := len(s)var buf bytes.Bufferfor i := 0; i < len%3; i++ {buf.WriteByte(s[i])}if len%3 != 0 {buf.WriteByte(',')}for i := len % 3; i < len; {buf.WriteString(s[i : i+3])i += 3if i != len { // 不是最后一组均写入','buf.WriteByte(',')}}// fmt.Println(buf.String())return buf.String()
}func test_3_11(num string) string {index := strings.LastIndex(num, ".")if index == -1 {return test_3_10(num) //不是浮点数直接返回} else {return test_3_10(num[:index]) + "." + num[index+1:] //浮点数先处理整数部分再连接后面浮点数返回}
}func main() {var num stringfmt.Print("please input a number:")_, _ = fmt.Scanln(&num)fmt.Println(test_3_11(num))
}

3.12 判断两个字符串是否是是相互打乱的

// 判断两个字符串是否是是相互打乱的
func test_3_12(s1, s2 string) bool {m := make(map[rune]int)for _, c := range s1 {m[c]++}for _, c := range s2 {m[c]--}for _, v := range m {if v != 0 {return false}}return true
}func main() {s1, s2 := "sdfghjkuytfvb", "kjhgfdstyubvf"fmt.Printf("first string is :%s\nsecond string is :%s\n", s1, s2)if test_3_12(s1, s2) {fmt.Println("them have same characters")} else {fmt.Printf("they don't have different characters")}
}

3.13 编写KB、MB的常量声明

const (KB = 1000MB = 1000 * KBGB = 1000 * MBTB = 1000 * GBPB = 1000 * TBEB = 1000 * PBZB = 1000 * EBYB = 1000 * ZB
)

【go语言圣经】习题答案 第三章相关推荐

  1. 数据结构c语言版第二版第三章课后答案,数据结构(C语言版)习题集答案第三章.doc...

    数据结构(C语言版)习题集答案第三章.doc 习题三3.1 3.10 3.13 3.5 3.6 3.15 3.17 3.19 3.24 3.29 3.31 3.51 给定操作序列P1P2P3PiPn( ...

  2. 8086微型计算机原理答案,8086微型计算机原理与应用(吴宁)习题答案(第三章)

    8086微型计算机原理与应用(吴宁)习题答案(第三章) 8086微型计算机原理与应用(吴宁)习题答案(第二章) 第三章 3-3 (1) 源操作数 为立即寻址方式:目的操作数为寄存器寻址方式 (2) 源 ...

  3. 《机器学习》周志华课后习题答案——第三章 (1-7题)

    <机器学习>周志华课后习题答案--第三章 (1-7题) 文章目录 <机器学习>周志华课后习题答案--第三章 (1-7题) 一.试析在什么情形下式(3.2)中不必考虑偏置项b. ...

  4. 【考研复习】《操作系统原理》孟庆昌等编著课后习题+答案——第三章

    前言 此书在最后的附录B中,有给出部分重难点部分的参考答案.会在最后放上图片.如果想要此书习题答案,可点以下链接:为一个压缩包,以图片形式,习题图片按章节排序,答案图片按书页排序. <操作系统原 ...

  5. Java语言程序设计基础篇(第十版 梁勇著)课后习题答案 - 第三章

    第三章:选择 复习题 3.1 列出 6 个关系操作符. 解: >,<,=,>=,<=,!= 3.2 假设 x 等于 1,给出下列布尔表达式的结果: (x > 0) (x ...

  6. 微型计算机原理与接口技术(周荷琴 冯焕清)第六版 课后习题答案 第三章(部分答案)

    第三章 1.分别说明下列指令的源操作数和目的操作数各采用什么寻址方式. 源操作数  目的操作数            源操作数                    目的操作数 (1)MOV AX, ...

  7. 《金融数据分析导论:基于R语言》习题答案(第一章)

     <金融数据分析导论:基于R语言>是芝加哥大学的教授Ruey S.Tsay所著,李洪成.尚秀芬.郝瑞丽翻译,机械工业出版社出版,是一本学习R语言和金融数据分析的很好的参考书籍. ** 注 ...

  8. 计算机网络谢希仁第七版课后习题答案(第三章)

    3-01数据链路(即逻辑链路)与链路(即物理链路)有何区别? "电路接通了"与"数据链路接通了"的区别何在? 答案:数据链路与链路的区别在于数据链路出链路外,还 ...

  9. 编译原理(第3版-王生原)课后习题答案-第三章

    1.构造下列正规式相应的 DFA. (1)1(0|1) *101 (2)1(1010* |1(010)*1) *0 (3)a((a|b)* |ab*a)*b (4)b((ab)* bb)*ab 答案: ...

最新文章

  1. 弹出窗口, 不显示工具栏等。
  2. CentOS bug修复指令集(阿里云漏洞修复方法)
  3. 如何处理SAP Fiori Launchpad错误消息:Could not start the app due to a configuration problem
  4. html文件转换成dwt文件,如何把dwt页面转换成html页面
  5. CTS(5)---Android8.0中CTS测试对于TEE的要求
  6. 基于matlab的prony方法实现,基于MATLAB的Prony方法实现
  7. 基于Python + Redis实现分布式锁
  8. 修复Joe主题静态资源为国内地址
  9. 广东工业大学研究生新生攻略
  10. 4月书讯 | 一大波好书来袭,最美华章四月天
  11. windows11家庭版安装hyperv-v
  12. 关于阅读理解,我们学的,都是错的
  13. 对逐飞总钻风和龙邱神眼摄像头引脚的解读
  14. 微信小程序修改switch组件的大小
  15. 小学学校计算机里的单机游戏,15年前的农村小网吧,那个时候只能玩这些单机游戏...
  16. 【技术分享】如何通过PPPOE拨号上网
  17. Tkinter实现人员管理系统(mongodb版)
  18. 图片按钮 imagebutton
  19. win10显示我的电脑图标
  20. 智慧管廊解决方案-最新全套文件

热门文章

  1. 相关性不等于因果性吗,为什么?
  2. ACPI(一)基本概念
  3. 运用C#在VS2017的PictureBox控件中绘制简易二自由度机械臂,并且让机械臂实现画直线、圆、人物轮廓及写字的功能。
  4. 离职员工讲述易到混乱:CEO在办公室煮面条、逼员工下跪
  5. linux-mint 搜狗输入法,linuxmint 搜狗输入法安装
  6. 每年90万吨!新奥股份与切尼尔能源签署LNG长期购销协议
  7. 鸿蒙系统 麒麟系统什么关系,鸿蒙系统和麒麟芯片之间有什么秘密,为何只有麒麟芯片才能升级?...
  8. SQL Server2000 版本区别及安装图解
  9. 如何规范公司所有应用分层?
  10. 鼠标移入操作兄弟元素