一、Julia之HelloWorld及案例

本文介绍Julia语言的安装方法,包括Windows平台下的二进制安装流程,并演示了基本的使用案例,如打印HelloWorld和一个复杂的BMI指数计算案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、安装

1、安装方式及系统

安装方式:

  • 二进制包安装
  • 编译安装

系统:

  • Windows
  • MacOS
  • Linux(多种Linux发行版本)

2、Windows(64 bit)二进制安装

官网下载地址:https://julialang.org/downloads/

安装

双击exe安装文件,一直默认下一步,选择安装目录即可!

卸载

卸载Julia,只需要将Julia的安装目录以及工作,目录(一般为%HOME%/.julia路径)直接删除,并将%HOME%/.juliarc.jl和%HOME%/.julia_history两个文件同时删除即可!

二、使用

1、命名规则与关键字

命名规则要求

  • 名称可以包含关键字,不能整体使用。
  • 大小写敏感
  • 名称中不能有算术运算符或者内部的标识符,包括@、#、$、%、^、&等。
  • 名称首字符必须是下划线、英文26个字母的小写或大写,或者编码大于0X00A0的Unicode字符

关键字

关键字是Julia语言的基本元素,用于关键的声明、标识或限定,一般是一串小写字母。

关键字粗略分类:

  • 类型声明:abstract、primitive、type、struct、function、macro、new
  • 权限标识:global、local、mutable、const、outer
  • 模块操作:module、baremodule、using、import、export
  • 逻辑结构:where、for、while、break、continue、if、elseif、else、in
  • 语句块:begin、quote、let、end、do
  • 混合编程:ccall

2、Hello World

Julia作为动态语言,不需要main入口函数,只需直接提供需要运行的语句即可。

交互式控制台使用

启动控制台

image-20201009170148748

打印HelloWorld

image-20201009171118375

3、复杂案例

image-20201010095732400

数组实现方式

heights = rand(Float64, 1000)
weights = rand(Float64, 1000)

heights = heights .* (1.8-1.5) .+ 1.5
weights = weights .* (100-30) .+ 30

bmi(w,h) = w / (h^2)

indexes = broadcast(bmi, weights, heights)

# 对BMI指数进行分类
# 1-体重过低, 2-正常范围, 3-肥胖前期, 4-I度肥胖, 5-II度肥胖, 6-III度肥胖

function bmi_category(index::Float64)
	class = 0
	if index  < 18.5
		class = 1
	elseif index < 24
		class = 2
	elseif index < 28
		class = 3
	elseif index < 30
		class = 4
	elseif index < 40
		class = 5
	else
		class = 6
	end
	
	class
end

classes = bmi_category.(indexes)


for c in [1 2 3 4 5 6]
	n = count(X -> (X==c),classes)
	println("category", c, " ", n)
end

image-20201009175841271

复合类型实现方式

mutable struct Person
	height
	weight
	bmi
	class
end


#定义集合类型存放数据
people = Set{Person}()

for i = 1:1000
	h = rand() * (1.8-1.5) + 1.5
	w = rand() * (100-30) + 30
	p = Person(h, w, 0, 0)
	
	push!(people, p) #将对象放入集合people中
	
end


# 计算BMI指数
function bmi(p :: Person)
	p.bmi = p.weight/(p.height^2) #计算BMI指数
	p.class = bmi_category(p.bmi) #分类,得到类别ID
end


# 对1000个样本执行BMI计算,并统计分布
categories = Dict()
for p ∈ people
	bmi(p)
	categories[p.class] = get(categories, p.class, 0) + 1
end

categories

image-20201009181245153

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值